Can one write a when statement and check if a list...
# announcements
s
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
You can, if there's no initial argument to the when then each case or whatever just needs to provide a boolean
at that point though it's essentially identical to if else with extra indentation, pretty much
s
Ah thanks. Instead I actually used the following, which is a bit simpler to read aswell
Copy code
when (value) {
    in array -> {}
}
n
if (value in array)
still seems quite a bit simpler to me, but hey, whatever you like 🙂
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
I'd guess that's not his only branch. A when never makes really sense with one branch 😄
n
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
👍 1