假设我有以下内容:
fun makeSound(val animal: Animal) = when(animal) {
is Lion -> animal.roar()
is TRex -> animal.roar()
is Cow -> animal.moo()
}
Run Code Online (Sandbox Code Playgroud)
通常我会通过简单地添加一个RoaringAnimal接口并询问is RoaringAnimal. 但是还有另一种方法可以将多个is子句组合成一个吗?
通常您可以按照 Yoni 的回答中所示组合这些子句。
但在特定情况下,在androar上定义,但不在 上定义,则不能。LionTRexAnimal
这是因为编译器插入了智能转换:
is Lion -> animal.roar()
Run Code Online (Sandbox Code Playgroud)
是真的
is Lion -> (animal as Lion).roar()
Run Code Online (Sandbox Code Playgroud)
但在is Lion, is TRex ->子句中,它不知道要插入什么类型。
原则上,编译器可以通过插入另一个来扩展以处理这种情况when:
is Lion, is TRex -> animal.roar()
Run Code Online (Sandbox Code Playgroud)
会成为
is Lion, is TRex -> when(animal) {
is Lion -> animal.roar() // works as before
is TRex -> animal.roar()
}
Run Code Online (Sandbox Code Playgroud)
但我没想到会发生这种事
更新:下面的答案是在指定的问题之前写的,该问题roar是animal参数上的方法。就现在的问题而言,下面的答案将不再有效,但它仍然显示了如何在一个when语句的一行中组合多个条件。
你可以组合它们:
fun makeSound(animal: Animal) = when(animal) {
is Lion, is TRex -> roar()
is Cow -> moo()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2834 次 |
| 最近记录: |