我有两个不同的 Kotlin 密封类的图像。
sealed class Fruit {
object Apple : Fruit()
object Orange : Fruit()
object Banana : Fruit()
}
sealed class Vegetables {
object Broccoli : Vegetable()
object Carrot : Vegetable()
object Spinach : Vegetable()
}
是否可以定义包含水果和蔬菜的类型?就像是Produce = Fruit | Vegetable
这样你就可以写出类似的东西
fun lookAtProduce(produce: Produce) {
when (produce) {
is Carrot -> {
return "Orange"
}
is Apple -> {
return "Red"
}
....
}
}
fun putItInSalad(vegetable: Vegetable) {
when (vegetable) {
is Spinach -> {
return true
}
is Carrot -> {
return false
}
.....
}
}