【发布时间】:2021-11-03 07:59:51
【问题描述】:
我将静态数据存储在枚举中。它们可以有很多,但它们具有相同的结构,由一个特殊的接口指定,以简化它们的工作。我在 Swift 中使用了类似的逻辑并且它可以工作,但是 Kotlin 不允许我使用这样的逻辑。
interface DataElement {
val code: UInt
val name: String
}
enum class DataEnum1: DataElement {
Apple {
override val code: UInt
get() = 1u
},
Orange {
override val code: UInt
get() = 2u
},
Watermelon {
override val code: UInt
get() = 3u
}
}
enum class DataEnum2: DataElement {
Blueberry {
override val code: UInt
get() = 4u
},
Strawberry {
override val code: UInt
get() = 5u
},
Blackberry {
override val code: UInt
get() = 6u
}
}
问题来了
fun someFun() {
val array = DataEnum1.values()
anotherFun(array) // TYPE MISMATCH
//Required:
//Array<PeripheralDataElement>
//Found:
//Array<DataEnum1>
}
fun anotherFun(items: Array<DataElement>) {
// some logic
}
【问题讨论】:
标签: android kotlin enums interface