when (expression generating nullable){
null -> handle null
x -> handle x for which compiler knows its not null anymore
}
j
Joffrey
09/11/2021, 10:41 AM
Extract the expressions on the right into functions with meaningful names
➕ 1
Joffrey
09/11/2021, 10:43 AM
Maybe I misunderstood your question, if you want to name
x
you can do so inside the `when`:
Copy code
when(val x = expression)
i
Ivan Brko
09/11/2021, 10:43 AM
ok, that's what i was wondering, thx
w
wbertan
09/11/2021, 10:43 AM
Yes, you can:
Copy code
fun maybe(): String? = null
fun asas() {
when (val maybe = maybe()){
null -> println("it was null!")
"something" -> println("maybe is something! Check: $maybe")
else -> println("I don't know what it is! Check: $maybe")
}
}
i
Ivan Brko
09/11/2021, 10:44 AM
thx both! 👍 👍 👍
i much prefer that (being able to write the whole thing as a single expression) than having to first assign value to x and do if/else on it