Null Safety
Use nullable types, safe calls, Elvis, and smart casts for null-safe code.
Code
// Nullable types
var name: String? = "Alice"
name = null
// Safe call
println(name?.length)
// Elvis operator for default
val len = name?.length ?: 0
println(len)
// Smart cast after null check
fun greet(who: String?) {
if (who != null) {
println("Hi $who, length=${who.length}") // smart-cast to String
} else {
println("No name")
}
}
greet("Bob")
greet(null)
// let for null-scoped work
name?.let { println("Got $it") }
// Not-null assertion (use sparingly)
// val forced = name!!
// Nullable receivers
fun String?.orEmpty(): String = this ?: ""
// lateinit for deferred non-null init
class Service {
lateinit var url: String
fun init() { url = "https://api.example.com" }
}
val svc = Service()
svc.init()
println(svc.url)Explanation
Kotlin separates nullable types with ? from non-null types, forcing the compiler to track nullability. Safe calls ?. and the Elvis operator ?: provide defaults without explicit checks. After an if-null check the compiler smart-casts the value to its non-null type, removing the need for redundant assertions.
More Kotlin Snippets
Data Classes
Model immutable data with auto-generated equals, copy, and destructuring.
Coroutines
Use launch, async, await, and structured concurrency with supervisorScope.
Extension Functions
Add methods to existing types with extensions and infix operators.
Sealed Classes
Model closed hierarchies and UI state with sealed classes and when.
When Expression
Branch on values, ranges, and types with when as statement or expression.
Collections
Filter, map, group, partition, and chunk with functional operators.