Loney Chou
09/19/2023, 5:20 AMc.
val foo = when {
condition1 -> a
condition2 -> {
if (condition3) {
break b // Here
}
// Long code
c
}
else -> d
}Jeff Lockhart
09/19/2023, 5:24 AMval foo = when {
condition1 -> a
condition2 -> {
if (condition3) {
b // Here
} else {
// Long code
c
}
}
else -> d
}
I'd break out the complexities of "long code" into a separate function as well.Loney Chou
09/19/2023, 5:26 AMJeff Lockhart
09/19/2023, 5:32 AMyield because when and if statements are already expressions. As long as each of your branches produces a proper value for foo, the code I just shared works for what you described. foo will equal a, b, c, or d, depending on the outcome of condition1, condition2, or condition3.sciack
09/19/2023, 5:44 AMval foo = when {
condition1 -> a
condition2 && condition3 -> b
condition2 ->
// Long code
c
else -> d
}sciack
09/19/2023, 5:45 AMLoney Chou
09/19/2023, 5:54 AMcondition2 && condition3 followed by another condition2 then. Not hurt that much.sciack
09/19/2023, 7:08 AMKlitos Kyriacou
09/19/2023, 8:38 AMval foo = run {
when {
condition1 -> a
condition2 -> {
if (condition3) {
return@run b
}
// Long code
c
}
else -> d
}
}
(Also, it defeats the purpose as it adds an extra level of indentation, which is exactly what you're trying to avoid.)ephemient
09/19/2023, 10:23 AMval foo = when {
condition1 -> a
condition2 -> run {
if (condition3) {
return@run b
}
// Long code
c
}
else -> d
}Loney Chou
09/19/2023, 5:16 PMcondition2 && condition3 because it's better than having two possible values yielded in a single when branch. That second condition2 acts like a fallback so it doesn't break the intent.Klitos Kyriacou
09/19/2023, 5:24 PMcondition2 doesn't have any side effects and doesn't take a long time to compute, there's no harm in repeating it.Jeff Lockhart
09/19/2023, 5:25 PMwhen and just use the boolean result.Wout Werkman
09/20/2023, 8:37 AMcondition1 is true 🙂. There is no one size fits all solutionJeff Lockhart
09/20/2023, 3:26 PM