AnyCompiler

Null Safety

A regular type like String can never hold null — the compiler guarantees it. To allow 'no value', you write the type with a trailing ? — String? — and the compiler then forces you to handle the null case before you can use whatever's inside.

?. (safe call) accesses a member only if the value isn't null, evaluating to null itself otherwise instead of throwing. ?: (the elvis operator) then supplies a fallback for exactly that null case.

fun describe(name: String?) {
    println(name?.length ?: -1)
}

fun main() {
    describe(null)
    describe("Kotlin")
}
Output
-1
6

What a real null-safety error looks like

Trying to put null into a non-nullable type isn't a warning — it's a compile error, full stop. This is genuinely what the compiler reports — captured from a real run, not written to look plausible:

fun main() {
    val name: String = null
    println(name)
}
Output
OpenJDK 64-Bit Server VM warning: Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.
Main.kt:2:24: error: null can not be a value of a non-null type String
    val name: String = null
                       ^

Nothing runs at all — in Java or C#, the equivalent mistake would compile fine and only blow up at runtime the first time that value was actually used. Next: arrays and lists — fixed-size arrays versus the growable List.

Practice exercise

Write a function describe(name: String?) that prints name's length, falling back to -1 if name is null. Call it with null.