Klitos Kyriacou
01/04/2023, 3:42 PMwhen (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 -> ... }
ephemient
01/04/2023, 3:50 PMephemient
01/04/2023, 3:52 PMwhen (expr) {
in Double.NEGATIVE_INFINITY..<5.5 -> ...
}
in this casephldavies
01/04/2023, 4:07 PMin
clause of a `when`:
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
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.")
}
}