Kotlin Tutorial · Kotlin Basics · Lesson 10 of 31

Kotlin Null Safety

Nullable types, safe calls, the Elvis operator, smart casts and why Kotlin code rarely throws NullPointerException.

Create a free account to save this page, take notes and track your progress. Sign in

Nullable types

A normal type can't hold null: val name: String = null doesn't compile. Add ? to allow it: String?. The compiler then makes you handle the null case before you use the value.

Nullable types and smart casts
fun main() {
    var nickname: String? = null
    println(nickname?.length)          // safe call: null
    nickname = "Ana"
    if (nickname != null) {
        println(nickname.length)       // smart cast: nickname is String here
    }
}

Output

null
3

Run this on your computer — see “Get Started” for setup.

Operators for nulls

  • ?. safe call: calls only if the value isn't null, otherwise the result is null.
  • ?: Elvis operator: a fallback when the left side is null (it can also return or throw).
  • !! asserts non-null and throws if it is null; avoid it.
  • ?.let { } runs a block only for non-null values.
Safe calls, Elvis and let
data class User(val name: String, val email: String?)

fun domainOf(user: User): String {
    val email = user.email ?: return "no email"
    return email.substringAfter("@")
}

fun main() {
    val users = listOf(User("Ana", "[email protected]"), User("Ben", null))
    for (u in users) {
        println("${u.name}: ${u.email?.uppercase() ?: "(none)"}")
        u.email?.let { println("  send welcome mail to $it") }
        println("  domain: ${domainOf(u)}")
    }
    println("42".toIntOrNull() ?: 0)
    println("x".toIntOrNull() ?: 0)
}

Output

Ana: [email protected]
  send welcome mail to [email protected]
  domain: example.com
Ben: (none)
  domain: no email
42
0

Run this on your computer — see “Get Started” for setup.

Test yourself

What does a ?: b evaluate to when a is null?

  1. null
  2. b
  3. a NullPointerException
  4. false
Show answer

Answer: b

Was this page helpful?