Mark Vogel
08/25/2023, 3:10 PMyield
keyword.
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 itephemient
08/25/2023, 3:18 PMwhen (value) {
"other" -> run {
if (true) {
return@run "test"
}
// Do something else etc.
Mark Vogel
08/25/2023, 7:32 PMwhen
but it worksJoffrey
09/28/2023, 8:49 AMval 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:
val result = when(value) {
"something" -> "";
"other" -> computeOther()
else -> "";
}
fun computeOther() {
if (true) {
return "test"
}
// Do something else etc.
return ""
}
I'd take both of those options over the run { .. }
block