使用通配符对多个值进行模式匹配 [英] Pattern matching on multiple values with a wildcard
问题描述
在Kotlin中,我们可以使用when
对给定值(例如
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"
}
我们还可以通过将两个值嵌套在Pair
中来同时对多个值进行模式匹配.
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"
}
现在,我想知道如何使用通配符同时对多个值进行模式匹配. 我尝试了以下两种方法,但均未成功:
Now, I'd like to know how to pattern match on multiple values at the same time with a wildcard. I tried the following two approaches without success:
when(Pair(value1, value2)) {
(1, _), (_, "One") -> "One"
(2, _), (_, "Two"), (3, _), (_, "Three") -> "Two or three"
else -> "The rest"
}
和
when(Pair(value1, value2)) {
(1, else), (else, "One") -> "One"
(2, else), (else, "Two"), (3, else), (else, "Three") -> "Two or three"
else -> "The rest"
}
如何匹配其中一个变量的大小写?
推荐答案
Kotlin不具备您可能从其他语言中了解到的模式匹配功能.参见此处,对该功能进行讨论: https://discuss.kotlinlang. org/t/destructuring-in-when/2391/18
Kotlin doesn't have the pattern matching capabilities that you might know from other languages. See here for a discussion on the feature: https://discuss.kotlinlang.org/t/destructuring-in-when/2391/18
when
不支持您的用例.
这篇关于使用通配符对多个值进行模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!