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.
is String
the first case achieves a similar effect. –
Viridescent is String
causes instanceof
check, while the code in the answer doesn't, it only compares the reference with null
. –
Gilly meaningOfLife
is immutable. There's no way around meaningOfLife!!.function()
when it's mutable, is it? –
Hower var
, so there's indeed no other way but to create another local val
. But when a variable is non-nullable and you only need smart cast for var
you can write something like myVar.let { when (it) { /*smart cast works here*/ } }
. –
Gilly 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")
println(meaningOfLife ?: "There is no meaning")
–
Curb © 2022 - 2025 — McMap. All rights reserved.
if
construct is more preferable for binary situations like this one. Has the exact same effect aswhen
here – Surinamwhen
is that it has room to grow. – Howerwhen
has nothing to grow for. Usingwhen
as a glorifiedif
is quite wasteful IMO – Surinamwhen
desugars to something that uses more resources than a plainif
. If not, then you have one less line and conditional expandability in contrast toif
. – Howerwhen
, I prepare myself to a multy-chose. So it would surprised me to find only a bi-chose. – Surinam