Null Safety
Nullable vs non-null
In Kotlin a normal type can never be null. Add ? to allow null, and the compiler forces you to handle it.
var a: String = "hi"
// a = null // ❌ won't compile
var b: String? = "hi"
b = null // ✅ allowed
// Safe call: returns null instead of crashing
println(b?.length)
// Elvis operator: provide a default
val len = b?.length ?: 0
Smart casts
fun printLength(text: String?) {
if (text != null) {
// inside here, Kotlin knows text is not null
println(text.length)
}
}