I'm trying to do something like this: ```val list ...
# announcements
m
I'm trying to do something like this:
Copy code
val list = listOf(1,2,3,4,5)
when (list) {
    all { it < 10 } -> foo()
    any { it % 2 == 0 } -> bar()
    else -> baz()
}
but it doesn't seem to be possible and I'm not sure why.
t
'when' does not put its argument into scope. It is (as of yet) only meant for type checks:
Copy code
when(result) {
    is Success -> println("yeah!")
    else -> println("oh no!")
}
You can however use when without an argument:
Copy code
when {
    list.all { it < 10 } -> foo()
    list.any { it % 2 == 0 } -> bar()
    else -> baz()
}
(I hope I got the terminology somewhat right 😬)
3
v
And 'when' matches its argument against all branches sequentially until some branch condition is satisfied. So if you expect 'foo' and 'bar' to work, then you need to do something like this:
Copy code
with(list) {
    var noMatch = true
    if (all { it < 10 }) {
        foo()
        noMatch = false
    }
    if (any { it % 2 == 0 }) {
        bar()
        noMatch = false
    }
    if (noMatch) baz()
}
m
makes sense now, thanks! what do you mean by saying that it doesn't put its argument into scope yet? Are there plans to change it? Do you have a tracking ticket link or something?
r
There are a number of open issues / proposals to augment the functionality of
when
. See this one for example (as well as its related isssues): https://youtrack.jetbrains.com/issue/KT-28359
👍 1