? 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 (expr) {
in Double.NEGATIVE_INFINITY..<5.5 -> ...
}
in this case
p
phldavies
01/04/2023, 4:07 PM
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.")
}
}