Kotlin example

How to check for null in Kotlin

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Use the safe call and the Elvis operator: user?.address?.city ?: "unknown" reads the value when every step is there and falls back otherwise. A plain if (x != null) also works, and after it the compiler treats x as non-null. x?.let { … } is the Kotlin form of Swift's if let. Avoid x!!: it gives you the value or throws java.lang.NullPointerException.

Kotlin puts null in the type: a String can never be null, a String? can. The compiler won't let you call length on a String? until you have dealt with the null case, so a null check in Kotlin is something the compiler asks for, not a habit you have to remember. The sections below cover the operators for that (?., ?:, ?.let), checking with if and smart casts, several nullable values at once, Boolean? in a condition, the compile error you get when you skip the check, and what !! does, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1Safe calls (?.) and the Elvis operator (?:)Recommended

x?.length is a safe call: it calls length when x holds a value and gives null when it doesn't, instead of throwing. Safe calls chain, so user?.address?.city stops at the first null. The Elvis operator a ?: b gives a when it is not null and b otherwise (turned sideways, ?: looks like Elvis Presley's quiff, hence the name). Together they replace most null checks with one expression. Map lookups and functions like toIntOrNull() return nullable values, so the same pair handles them.

SafeCallElvis.kt
data class Address(val city: String?)
data class User(val name: String, val address: Address?)

fun cityOf(user: User?): String = user?.address?.city ?: "unknown"

fun main() {
    val text: String? = "Kotlin"
    val none: String? = null

    // ?. calls the method only when the value is not null
    println(text?.length)
    println(none?.length)

    // ?: (Elvis) gives a fallback when the left side is null
    println(none?.length ?: 0)
    println(none ?: "default")

    // Chains stop at the first null
    val users = listOf(
        User("Ada", Address("London")),
        User("Linus", Address(null)),
        User("Grace", null),
    )
    for (user in users) println("${user.name}: ${cityOf(user)}")
    println(cityOf(null))

    // Map lookups and toIntOrNull() return nullable values too
    val stock = mapOf("apple" to 3)
    println("figs: ${stock["fig"] ?: 0}")
    println("n = ${"42x".toIntOrNull() ?: -1}")
}

Output

text?.length prints 6, and the same call on the null value prints null rather than crashing. Add ?: 0 and you get 0, a plain Int. Linus has an address with no city and Grace has no address at all; the chain gives null for both, and the Elvis turns it into unknown. Note the type of cityOf: it returns String, not String?, because the Elvis guarantees a value. The missing map key gives figs: 0, and the text that is not a number gives n = -1.

2if (x != null), smart casts and ?: return

The check you know from Java works too, and does more: after if (x != null), the compiler smart-casts x to the non-null type inside the block, so you call methods on it directly. The same happens after an early exit, if (x == null) return, for the rest of the function. The Elvis operator does this in one line: val n = name ?: return or ?: throw works like Swift's guard let. For strings, isNullOrEmpty() and isNullOrBlank() check null and empty in one call.

SmartCast.kt
fun greet(name: String?): String {
    // ?: return leaves early; n is a plain String after this line
    val n = name ?: return "no name"
    return "Hello, $n (${n.length} letters)"
}

fun port(value: String?): Int =
    value?.toIntOrNull() ?: throw IllegalArgumentException("bad port: $value")

fun main() {
    val nickname: String? = "kit"

    // The Java-style check works, and the compiler remembers it
    if (nickname != null) {
        println("${nickname.uppercase()} has ${nickname.length} letters")
    }

    println(greet("Ada"))
    println(greet(null))

    println(port("8080"))
    try {
        port("eighty")
    } catch (e: IllegalArgumentException) {
        println(e.message)
    }

    // && smart-casts both values at once
    val width: Int? = 1920
    val height: Int? = 1080
    if (width != null && height != null) {
        println("area ${width * height}")
    }

    // Null, empty and blank in one call
    for (s in listOf(null, "", "  ", "ok")) {
        println("[$s] empty=${s.isNullOrEmpty()} blank=${s.isNullOrBlank()}")
    }
}

Output

Inside the if, nickname.uppercase() needs no ?. and prints KIT has 3 letters. greet(null) leaves at the Elvis with no name, and port("eighty") throws bad port: eighty. One && check smart-casts both numbers, so width * height compiles and prints area 2073600. The last loop shows the difference between the string helpers: [ ] is not empty but is blank. Smart casts work on local vals and vars, not on a var property of a class, which another thread could change between check and use; that error is covered in check a type at runtime.

3?.let: Kotlin’s if let, and code that runs on null

x?.let { … } runs the block only when x is not null, with the value as it (or a name you give it). It is the usual answer to "what is Swift's if let in Kotlin", and it is handy at the end of a chain, where there is no variable to check with if. For the opposite case, code that runs only when the value is null, use x ?: run { … } or a plain if (x == null). Kotlin has no multi-variable let; for two values, nest the calls, use the && check from section 2, or write a small helper.

LetIfNotNull.kt
inline fun <A : Any, B : Any, R> ifBoth(
    a: A?,
    b: B?,
    block: (A, B) -> R,
): R? = if (a != null && b != null) block(a, b) else null

fun main() {
    val email: String? = "[email protected]"
    val phone: String? = null

    // ?.let runs the block only when the value is not null
    email?.let { println("send to $it") }
    phone?.let { println("call $it") }

    // Name the value instead of using it
    email?.let { address ->
        println("domain: ${address.substringAfter('@')}")
    }

    // Run code only when the value is null
    phone ?: run { println("no phone on file") }

    // if not null, else: let + Elvis gives one value
    val contact = phone?.let { "phone $it" } ?: "email $email"
    println(contact)

    // Trap: ?: run also fires when the let block itself returns null
    email?.let { null } ?: run { println("run ran, but email was not null") }

    // An if/else expression has no such trap
    val label = if (phone != null) "phone $phone" else "no phone"
    println(label)

    // Two values: nested lets work but read badly
    val first: String? = "Ada"
    val last: String? = "Lovelace"
    first?.let { f -> last?.let { l -> println("$f $l") } }

    // A small helper reads better
    println(ifBoth(first, last) { f, l -> "$l, $f" })
    println(ifBoth(first, phone) { f, p -> "$f: $p" })
}

Output

The email block runs and prints send to [email protected]; the phone block is skipped without a sound, and the run block prints no phone on file instead. The fifth line is the trap people hit with x?.let { … } ?: run { … } as an if/else: the Elvis looks at what the let block returned, so a block that ends in null (or in a call that returns null) runs the "else" part too. When you need a real if/else, write if (x != null) … else …, which is also an expression. The helper returns Lovelace, Ada when both values are there and null when one is missing.

4Boolean? in an if

A Boolean? has three states: true, false and null. if (flag) doesn't compile; here the error reads Condition type mismatch: inferred type is 'Boolean?' but 'Boolean' was expected. You have to say what null means. flag == true treats null as false, flag != false treats it as true, and flag ?: false names the default outright. A when with all three cases handles each one on its own.

NullableBoolean.kt
data class Settings(val darkMode: Boolean?)

fun main() {
    val all = listOf(Settings(true), Settings(false), Settings(null))

    for (s in all) {
        val flag = s.darkMode
        // == true: only a real true passes; false and null do not
        val on = if (flag == true) "on" else "off"
        // != false: true and null pass (null counts as "yes")
        val notOff = flag != false
        // ?: false picks the default for null explicitly
        val orFalse = flag ?: false
        println("$flag -> $on, notOff=$notOff, orFalse=$orFalse")
    }

    // when covers all three states
    for (s in all) {
        val text = when (s.darkMode) {
            true -> "dark"
            false -> "light"
            null -> "follow the system"
        }
        println(text)
    }
}

Output

The first two rows agree everywhere; the null row is where the forms differ: == true gives off, != false gives notOff=true, and ?: false gives orFalse=false. Pick the one that matches what a missing value should mean, and prefer flag == true or flag ?: false over flag != false, which is easy to misread. The when needs no else because true, false and null cover every value.

5The compile error: “Only safe (?.) or non-null asserted (!!.) calls”

Calling a method on a nullable value without a check doesn't compile. The program below never runs: findUser returns String?, and name.length would crash if the user were missing, so the compiler stops first. This is the error that sends people looking for !!.

NullableReceiver.kt
fun findUser(id: Int): String? = if (id == 1) "Ada" else null

fun main() {
    val name = findUser(1)
    println(name.length)
}

Output

The compiler stops with Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type 'String?'. It names both ways out, and the first is the one to reach for: change line 5 to println(name?.length ?: 0), or wrap it in if (name != null), and run it again. The second, !!, is the next section. A related error, Null cannot be a value of a non-null type 'String'., appears when you assign null to a String: add the ? to the type if null is a real possibility.

6The !! operator and NullPointerException

x!!, the not-null assertion (the "double bang"), turns a String? into a String by promise: if the value is there you get it, and if it is null Kotlin throws java.lang.NullPointerException. That is the difference from ?., which turns the null into a null result and keeps going. Use !! only when null would be a bug in your own code. When you do want a crash on null, requireNotNull and checkNotNull throw with a message you choose, which beats an empty exception in a log.

NotNullAssertion.kt
fun findUser(id: Int): String? = if (id == 1) "Ada" else null

fun main() {
    // !! turns String? into String, or throws if it is null
    val ada = findUser(1)!!
    println("${ada.length} letters")

    // requireNotNull and checkNotNull throw with your own message
    try {
        val user = requireNotNull(findUser(2)) { "no user with id 2" }
        println(user)
    } catch (e: IllegalArgumentException) {
        println("${e::class.simpleName}: ${e.message}")
    }

    // !! on null throws NullPointerException with no message
    val missing = findUser(3)!!
    println(missing.length)
}

Output

findUser(1)!! has a value, so 3 letters prints. requireNotNull throws an IllegalArgumentException carrying no user with id 2 (checkNotNull throws IllegalStateException the same way). The last !! meets null and the program stops with Exception in thread "main" java.lang.NullPointerException and at MainKt.main(Main.kt:17): no message, only the line number of the !! that failed. The two lines printed before the crash still show.

7Which should you use?

MethodWhen nullResult typeBest for
x?.prop ?: defaultUses the defaultNon-nullA value with a sensible fallback
if (x != null) { … }Skips or runs elseSmart-cast insideSeveral lines that use the value, two values at once
val v = x ?: returnLeaves the functionNon-null afterValues a function needs before it can go on
x?.let { … }Skips the blockNullableThe end of a chain, a short action on the value
x?.propGives nullNullablePassing the null along
requireNotNull(x) { … }Throws, your messageNon-nullArguments that must be there
x!!NullPointerExceptionNon-nullValues that are null only if your code has a bug

Frequently asked questions

What is the !! operator in Kotlin?

!! is the not-null assertion operator, often called the double bang. x!! gives the value of a nullable x as a non-null type, and throws java.lang.NullPointerException when x is null. Treat each !! as a place your program can crash, and prefer ?., ?: or an if check when null is a real possibility.

What is the difference between !! and ? in Kotlin?

Both let you call a method on a nullable value. x?.length is a safe call: when x is null the whole expression is null and the program goes on, so the result type is Int?. x!!.length asserts that x is not null: the result is a plain Int, and a null x throws NullPointerException. A ? after a type, as in String?, is a different thing: it declares that the type can hold null.

What does ?: do in Kotlin?

a ?: b is the Elvis operator. It gives a when a is not null and evaluates b otherwise, so name ?: "guest" gives a non-null String. The right side can also be return or throw, which turns val n = name ?: return into an early exit that leaves n non-null for the rest of the function.

What is the Kotlin equivalent of Swift's if let and guard let?

For if let, use if (x != null) { … } on a local value, where the compiler smart-casts x inside the block, or x?.let { … } on an expression or the end of a chain. For guard let, use the Elvis operator with an exit: val user = findUser(id) ?: return.

How do I run a block of code only when a value is null?

Write if (x == null) { … }, or x ?: run { … } inside an expression. Be careful with x?.let { … } ?: run { … } as an if/else: the run block also runs when x is not null but the let block returns null. When you need both branches, if (x != null) … else … is safer.

How do I check several nullable values at once?

Put them in one condition: if (a != null && b != null) { … } smart-casts both inside the block. Kotlin has no multi-variable let; nested a?.let { x -> b?.let { y -> … } } works but reads badly, and a small inline helper such as ifBoth(a, b) { x, y -> … } keeps call sites short.

Can Kotlin code still throw NullPointerException without !!?

Yes, at the edges with Java. Most Java methods carry no nullability information, so Kotlin trusts your declaration: val home: String = System.getenv("NO_SUCH_VAR") compiles, then throws java.lang.NullPointerException: getenv(...) must not be null at that line. Declare such values as String? and check them. An explicit throw NullPointerException() and Java code that throws one also still do.

Run it yourself

Open any of these in the full Kotlin editor to tweak, run and share.

Kotlin playground