Pattern matching on multiple values at the same time

3.2k views Asked by At

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?

2

There are 2 answers

0
Neo On

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"
}
0
ndelanou On

I guess you could use the when pattern without parameter:

val value1: Int = ? 
val value2: String = ?

when {
    value1 == 1 && value2 == "One" -> "One"
    value1 == 2 && value2 == "Two" || value1 == 3 && value2 == "Three" -> "Two or three"
    else -> "The rest"
}