考虑一下这个极其简化的代码(在https://pl.kotl.in/bb2Irv8dD上可用):
sealed class Person {
data class A(val i: Int) :
Person()
}
fun main() {
val a = Person.A(i = 0)
val b = Person.A(i = 1)
// Compiles
when (a) {
is Person.A -> print("I have access to {$a.i}")
}
// Does not compile :(
when (a to b) {
is Person.A to is Person.A -> print("I have access to {$a.i} and b {$b.i}")
}
}
为什么(a to b)
代码不起作用?它适用于1个变量,我希望我可以在两个类上匹配,并获得两个内部值.
错误是:
不兼容的类型:Person.A和Pair<;Person.A,Person.A>;预期 "->;"需要元素不兼容的类型:Person.A和 Pair<;Person.A,Person.A>;