Is there a reason the only operators allowed in `w...
# language-evolution
k
Is there a reason the only operators allowed in
when (expr) { ... }
blocks are just the four specific operators
is
,
!is
,
in
and
!in
? It seems quite arbitrary to limit the allowed operators instead of saying you can have any binary operator with just its right-hand side (for example,
when (temperature) { < 5.5 -> ... }
as a workaround, you should be able to
Copy code
when (expr) {
    in Double.NEGATIVE_INFINITY..<5.5 -> ...
}
in this case
p
I in no way advocate doing this, but you could always provide an extension operator for contains on any arbitrary type/object/function/reference and use that in the
in
clause of a `when`:
Copy code
operator fun <T> ((T) -> Boolean).contains(it: T) = invoke(it)

fun main() {   
    println(when(123) {
        in { it: Int -> it > 5 } -> "more than 5"
        else -> "not."
    })
    
    println(when(' ') {
        in Char::isWhitespace -> "space!!"
        in Char::isLowerCase -> "lower."
        else -> "not space."
    })
}
or using a fun interface
Copy code
fun interface Match<T> {
    operator fun contains(it: T): Boolean
}
fun <T> match(predicate: (T) -> Boolean) = Match(predicate)

fun main() {
    when("hello") {
        in match<String> { it.startsWith("hell") } -> println("o.")
    }
}