Can one write a when statement and check if a list contains a value?
Like the following (pseudocode):
Copy code
when {
array.contains(value) -> {
}
}
yes black 1
n
Nir
01/07/2021, 10:48 PM
You can, if there's no initial argument to the when then each case or whatever just needs to provide a boolean
Nir
01/07/2021, 10:48 PM
at that point though it's essentially identical to if else with extra indentation, pretty much
s
spnda
01/07/2021, 10:54 PM
Ah thanks.
Instead I actually used the following, which is a bit simpler to read aswell
Copy code
when (value) {
in array -> {}
}
n
Nir
01/07/2021, 11:00 PM
if (value in array)
still seems quite a bit simpler to me, but hey, whatever you like 🙂
Nir
01/07/2021, 11:00 PM
if
value
is coming from a complex expression another option is
value.takeIf { it in array }
which can be useful depending what you're doing
v
Vampire
01/07/2021, 11:03 PM
I'd guess that's not his only branch. A when never makes really sense with one branch 😄
n
Nir
01/07/2021, 11:15 PM
yeah, taht's true, thought I'd still mention the
takeIf
in case though 🙂 But with multiple branches I'd still be inclined to if/else-if, really more because of indentation than anything else, but it's all to taste at that point