Explanation of Kotlin's advanced concepts, ideal for leveling up after learning the basics
Absolutely! Here's a clear explanation of Kotlin's advanced concepts, ideal for leveling up after learning the basics.
🔷 1. Null Safety
Kotlin helps prevent NullPointerException
errors at compile time.
var name: String? = null // Nullable type
println(name?.length) // Safe call (prints null)
-
?
→ means the variable can be null. -
?.
→ safe access; won't crash if it's null. -
!!
→ force access; crashes if null (use carefully). -
?:
→ Elvis operator (default value if null).
val length = name?.length ?: 0
🔷 2. Lambda Expressions
Functions that can be passed as values.
val greet = { name: String -> "Hello, $name!" }
println(greet("Kotlin")) // Output: Hello, Kotlin!
Used a lot in higher-order functions like map
, filter
, forEach
.
val numbers = listOf(1, 2, 3)
numbers.forEach { println(it) }
🔷 3. Higher-Order Functions
Functions that take other functions as parameters or return them.
fun operate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
val sum = operate(5, 3) { x, y -> x + y }
println(sum) // Output: 8
🔷 4. Extension Functions
Add functionality to existing classes without modifying them.
fun String.reverse(): String {
return this.reversed()
}
println("Kotlin".reverse()) // Output: niltoK
🔷 5. Data Classes
Used to hold data with automatic equals()
, hashCode()
, toString()
, and copy()
.
data class User(val name: String, val age: Int)
val u = User("Sam", 30)
println(u) // Output: User(name=Sam, age=30)
🔷 6. Sealed Classes
A type-safe way to handle limited sets of types (often used in when
expressions).
sealed class Result
data class Success(val data: String) : Result()
object Error : Result()
fun handle(result: Result) = when (result) {
is Success -> println(result.data)
Error -> println("Error occurred")
}
🔷 7. Coroutines
Used for asynchronous programming (e.g., networking, database).
suspend fun fetchData() {
delay(1000)
println("Data loaded")
}
GlobalScope.launch {
fetchData()
}
Kotlin uses suspend
, launch
, and async/await
for background work in a clean way.
🔷 8. Generics
Used to write reusable classes/functions that work with any type.
fun <T> display(item: T) {
println(item)
}
display("Hello")
display(123)
Would you like to focus deeper on any of these (like coroutines or extension functions) with examples and practice?
Comments
Post a Comment