typestar

Nullable types in Kotlin

null is in the type system: String? admits it, String never will.

fun main() {
    // String? admits null; plain String never does.
    val radioCheck: String? = null
    val relay: String? = "Windy Col repeater"

    // ?. stops at null; ?: supplies the fallback.
    println(radioCheck?.length ?: "no signal")
    println(relay?.uppercase() ?: "no signal")

    val beds: Int? = mapOf("Larkspur" to 18)["Stone"]
    val planned = beds ?: 0
    println("Planning on $planned beds")
}

How it works

  1. val radioCheck: String? may hold null; plain String cannot.
  2. ?. stops the chain at null instead of throwing.
  3. ?: — the Elvis operator — supplies the value for the null case.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
382
Tokens
78
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 67 seconds.

Type this snippet

Step 1 of 3 in Null safety, step 16 of 27 in Language basics.

← Previous Next →

Nullable types in other languages