Null safety and !!

Kotlin language Junior Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Predict the output

What does this print?

fun main() {
    val name: String? = null
    val length = name?.length ?: -1
    println(length)
    try {
        println(name!!.length)
    } catch (e: NullPointerException) {
        println("NPE")
    }
}
Options
Hint 1 of 1

What does name?.length return for null?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A -1, then NPE

Correct. The safe call gives null, ?: supplies -1, and !! throws NullPointerException.

Why not the others?
  • B 0, then NPE. ?. returns null, not 0.
  • C -1, then 0. !! on null throws.
  • D It doesn't compile. All of this is valid Kotlin.

30-second answer

Types are non-null by default; String? can hold null and the compiler forces you to handle it. Use ?. for safe calls, ?: for a default, let to run code only when non-null, and smart casts after a null check. !! tells the compiler 'trust me' and throws a NullPointerException if the value is null.

Practise saying it · 30 s. No recording, just a timer

Explain Kotlin null safety.

Say your answer out loud, then check which of these points you covered:

  • Non-null by default
  • ?. ?: let and smart casts
  • !! throws NullPointerException
  • Platform types from Java

Deep dive

Platform types from Java (String!) aren't checked; annotate Java code with @Nullable/@NonNull so Kotlin sees real types.

lateinit and !! both move null errors to runtime; prefer constructor parameters or lazy.

requireNotNull(x) { "message" } and checkNotNull throw with a useful message.

filterNotNull() and mapNotNull keep null handling out of loops.

Common mistakes

  • Scattering !! to silence the compiler.
  • Trusting values from Java APIs without null checks.
  • Using ?.let { } ?: run { } chains that are harder to read than an if.

Senior take & follow-ups

Mention platform types; that's where Android apps still get NPEs.

Follow-up questions

Think of your answer first, then open the hint.

  1. What exception does !! throw?

    Show hint

    NullPointerException.

  2. When is !! acceptable?

    Show hint

    Rarely, when a null would be a programming error and crashing early is wanted; requireNotNull gives a better message.

Suggest a fix if something here is wrong or out of date.