Null Safety

One of Kotlin’s headline features: the type system distinguishes values that can be null from those that cannot, eliminating most NullPointerExceptions at compile time.

Nullable vs non-null types

var name: String = "Kotlin"
// name = null            // compile error: String cannot hold null

var nickname: String? = "Kot"  // String? CAN hold null
nickname = null                // OK

A ? after the type makes it nullable. Without it, the value is guaranteed non-null.

Safe calls ?.

Call a member only if the receiver is non-null; otherwise the whole expression is null:

val length: Int? = nickname?.length   // null if nickname is null

The Elvis operator ?:

Provide a fallback when the left side is null:

val len = nickname?.length ?: 0       // 0 if nickname is null
val n = nickname ?: "unknown"

The not-null assertion !!

!! forces a nullable into a non-null, throwing a NullPointerException if it is actually null:

val forced = nickname!!.length        // throws if nickname is null

Avoid !! unless you can guarantee the value is non-null. It throws away the safety the type system gives you. Prefer ?. and ?:.

Safe casts as?

val obj: Any = "hello"
val str: String? = obj as? String     // null if the cast would fail

let for null handling

Run a block only when a value is non-null:

nickname?.let { value ->
    println("Nickname is $value")      // runs only if non-null
}

Platform types (Java interop)

Values coming from Java have unknown nullability (“platform types”). Treat them carefully and annotate or wrap them as nullable when in doubt — more on this in Part 7.

Exercises

  1. Given val middle: String? = null, print its length or 0 using the Elvis operator.

  2. Write lengthOrZero(s: String?): Int that returns the string’s length, or 0 when it is null — without using if.

    Solution
   fun lengthOrZero(s: String?): Int = s?.length ?: 0
   

</details>


Previous: Strings · Next: Control Flow


Back to top

Kotlin & Android Programming Guide is not affiliated with JetBrains or Google. Content is provided for educational purposes.

This site uses Just the Docs, a documentation theme for Jekyll.