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
val radioCheck: String?may hold null; plainStringcannot.?.stops the chain at null instead of throwing.?:— the Elvis operator — supplies the value for the null case.
Keywords and builtins used here
funmainval
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.
Step 1 of 3 in Null safety, step 16 of 27 in Language basics.