Search code examples
kotlincontrol-flow

How to pattern match optionals in Kotlin?


Is it possible to write something like this, or do we have to revert back to manual null checking in Kotlin?

val meaningOfLife : String? = null

when meaningOfLife {
    exists -> println(meaningOfLife)
    else   -> println("There's no meaning")
}

Solution

  • One of possible ways is to match null first so that in else branch the String? is implicitly converted to String:

    val meaningOfLife: String? = null
    
    when (meaningOfLife) {
        null -> println("There's no meaning")
        else -> println(meaningOfLife.toUpperCase()) //non-nullable here
    }
    

    This is a special case of a smart cast performed by the compiler.

    Similar effect can be achieved with is String and else branches -- is String-check is true when the value is not null.

    For more idioms regarding null-safety please see this answer.