In Kotlin, we can use when
to pattern match on a given value, e.g.,
when(value) {
1 -> "One"
2, 3 -> "Two or three"
else -> "The rest"
}
We can also pattern match on multiple values at the same time by nesting the two values in a Pair
.
when(Pair(value1, value2)) {
(1, "One") -> "One"
(2, "Two"), (3, "Three") -> "Two or three"
else -> "The rest"
}
Are there better ways of pattern matching on two values at the same time than nesting the two values in a pair?
I don't have a better solution, but a syntax suggestion to write the Pair
example more elegantly (as requested in comment):
val value1 = 1
val value2 = "One"
when(value1 to value2) {
1 to "One" -> "One"
2 to "Two", 3 to "Three" -> "Two or three"
else -> "The rest"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With