gpt4 book ai didi

generics - 在 Kotlin 中的 when 子句中组合多个

转载 作者:行者123 更新时间:2023-12-02 12:14:47 25 4
gpt4 key购买 nike

假设我有以下内容:

fun makeSound(val animal: Animal) = when(animal) {
is Lion -> animal.roar()
is TRex -> animal.roar()
is Cow -> animal.moo()
}

通常我会通过简单地添加一个 RoaringAnimal 来简化它界面和询问 is RoaringAnimal .但是还有另一种组合多个 is 的方法吗?条款合二为一?

最佳答案

更新 : 下面的答案写在问题指定 roar 之前是 animal 上的一个方法范围。现在的问题是,下面的答案将不再有效,但它仍然显示了如何在 when 中的一行中组合多个条件。陈述。

你可以组合它们:

fun makeSound(animal: Animal) = when(animal) {
is Lion, is TRex -> roar()
is Cow -> moo()
}

关于generics - 在 Kotlin 中的 when 子句中组合多个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53338396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com