【发布时间】:2023-03-18 20:15:01
【问题描述】:
我有两个不同的 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
}
.....
}
}
【问题讨论】:
标签: kotlin sealed-class