I often run into circumstances where I want to sho...
# general-advice
m
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
Copy code
when (value) {
    "other" -> run {
        if (true) {
            return@run "test"
        }
        // Do something else etc.
🙌 1
m
That makes sense just run a lambda haha not really native support in
when
but it works
j
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 ""
}
I'd take both of those options over the
run { .. }
block