Kotlin null safety on one page
The five tools Kotlin gives you for values that might be missing, with one tiny example each.
#kotlin#learning
In Kotlin, a normal type can't hold null. You have to ask for it with a ?.
val name: String = "Lalan" // never null
val nickname: String? = null // may be nullThe compiler then makes you handle the null case. Here are the five tools.
?. safe call
Call it only if it's not null. Otherwise the whole thing is null.
val length: Int? = nickname?.length?: Elvis operator
Give a fallback when the left side is null.
val shown: String = nickname ?: "No nickname"!! "trust me"
Says "this is not null". If it is, the app crashes with a NullPointerException. Use it almost never.
val sure: Int = nickname!!.length // crashes if nickname is nullSmart cast
After you check for null, Kotlin remembers it.
if (nickname != null) {
println(nickname.length) // no ?. needed here
}?.let { }
Run a block only when the value exists.
nickname?.let { println("Hi, $it") }