Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching on multiple values at the same time

Tags:

kotlin

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?

like image 354
Little Helper Avatar asked Oct 16 '25 13:10

Little Helper


1 Answers

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"
}
like image 141
Neo Avatar answered Oct 18 '25 08:10

Neo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!