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")
}
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")
}
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.
You can accomplish that as follows:
val meaningOfLife: String? = null
when (meaningOfLife) {
is String -> println(meaningOfLife)
else -> println("There's no meaning")
}
FYI, the particular situation in the question has a way simple solution with the ?: operator of default value:
println(meaningOfLife ?: "There's no meaning")
The example in the question is probably a simplified real situation, so a null check is how I would do it. IMHO if is a better way to go when you have a binary chose of control flow:
if(meaningOfLife != null)
println(meaningOfLife)
else
println("There's no meaning")
Takes exactly the same number of lines, BTW.
Try this:
val meaningOfLife : String? = null
meaningOfLife?.let { println(it) } ?: println("There's no meaning")