Kotlin实际上没有patterns个,就像C#、Swift或Haskell中的recursive个模式匹配而言.
when
和类似的参数seems可以进行模式匹配,但实际上,大小写在when
中只支持有限数量的操作(请参见language spec):
- 判断参数的类型-
is SomeType
,!is SomeType
.如果判断成功,则该类型的参数也将为smart-casted.
- 正在判断安全壳-
in someCollection
,!in someCollection
.这基本上就是呼叫contains
.
- 根据任何其他表达式判断相等性.
else
个
你不能用其他语言做同样的事情.
假设a
和b
的类型未知,我将使用if
编写以下代码:
if (a is String && b is Int) {
// a and b will be smart-casted inside here
} else {
// do something else
}
如果有多个 case ,您可以使用when
或without个参数.
// a and b will be smart-casted to the appropriate types in each case
when {
a is String && b is Int -> ...
a is Int && b is String -> ...
// and so on
}
请注意,从a
和b
算出Pair
并判断配对的类型不起作用:
when (a to b) {
is Pair<String, Int> -> ...
...
}
这是因为泛型类型在运行时被擦除.运行库不知道它是Pair<String, Int>
、Pair<Int, String>
还是任何其他类型的Pair
.它只能判断自己确实是一架Pair
,而不是String
或Triple
.