fun main() {
val name: String = "Alice" // never null
val maybe: String? = null // explicitly nullable
// name.length // OK — compiler knows it can't be null
// maybe.length // ✗ compile error: receiver may be null
// Three ways to handle the nullable safely:
// 1. Safe call ?. — returns null if receiver is null
val len: Int? = maybe?.length
println(len) // null
// 2. Elvis ?: — supply a fallback
val len2: Int = maybe?.length ?: 0
println(len2) // 0
// 3. Not-null assertion !! — throws NPE if null (use sparingly)
val len3: Int = maybe!!.length // NullPointerException here
// 4. Smart cast after a null check
if (maybe != null) {
println(maybe.length) // smart-cast to non-null String
}
}
Create a free account and build your private vault. Share publicly whenever you want.