I often run into circumstances where I want to short circuit a when statement. In Java (as of the later versions) you can do this with the
yield
keyword.
Copy code
var result = switch (value) {
case "something" -> "";
case "other" -> {
if (true) {
yield "test";
}
// Do something else etc.
yield "";
}
default -> "";
};
Does Kotlin have something analogous? It seems
return@when
doesn't work and that's all I can think of, but can't find anything online that talks about it
e
ephemient
08/25/2023, 3:18 PM
Copy code
when (value) {
"other" -> run {
if (true) {
return@run "test"
}
// Do something else etc.
🙌 1
m
Mark Vogel
08/25/2023, 7:32 PM
That makes sense just run a lambda haha not really native support in
when
but it works
j
Joffrey
09/28/2023, 8:49 AM
I know I'm late here, but I just stumbled upon this by chance.
I wanted to say FTR that this is also possible:
Copy code
val result = when(value) {
"something" -> "";
"other" -> if (true) {
"test"
} else {
// Do something else etc.
""
}
}
else -> "";
}
But if you have a decent-sized chunk of code in here, I'd definitely recommend extracting it to a function, which can have
return
in it:
Copy code
val result = when(value) {
"something" -> "";
"other" -> computeOther()
else -> "";
}
fun computeOther() {
if (true) {
return "test"
}
// Do something else etc.
return ""
}