The Garden

ProjectsApps and devices I have built, for clients and for myselfProductsIdeas I own, build and ship myselfBlogLonger writing about building apps, devices and productsNotesLoose notes on things I'm still learning
← Notes/seedling

Kotlin null safety on one page

The five tools Kotlin gives you for values that might be missing, with one tiny example each.

Planted 28 Nov 20261 min read
#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 null

The 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 null

Smart 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") }