科特林。接口作为参数

Tim*_*lin 2 enums android interface kotlin

我将静态数据存储在枚举中。它们可以有很多,但它们具有相同的结构,由特殊的接口指定,以简化所有它们的工作。我在 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
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是这样的

fun someFun() {
  val array = DataEnum1.values()
  anotherFun(array) // TYPE MISMATCH
  //Required:
  //Array<PeripheralDataElement>
  //Found:
  //Array<DataEnum1>
}
    
fun anotherFun(items: Array<DataElement>) {
     // some logic
}
Run Code Online (Sandbox Code Playgroud)

mar*_*ran 5

数组在 Kotlin 中是不变的,这意味着您不能直接将 a 传递Array<SubClass>给接受 的函数Array<SuperClass>。但是,您可以像这样定义函数以使其接受协变数组:

fun anotherFun(items: Array<out DataElement>) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

现在你的函数也接受Array<SubClass>.

旁注:这会自动与列表一起使用,因为List在接口级别的类型参数中被定义为协变,例如interface List<out T>.