android - Kotlin 。接口(interface)作为参数

标签 android kotlin enums interface

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

最佳答案

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

fun anotherFun(items: Array<out DataElement>) {
    // ...
}

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

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

关于android - Kotlin 。接口(interface)作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69070977/

相关文章:

Java7/枚举构造函数/Files.createTempDirectory(String prefix, FileAttribute<?>... attrs)

android - 在 android 中使用枚举

android - testProguardFiles 忽略了我的规则。无法针对发布构建类型运行 Espresso 测试

android - Webview 错误未捕获 SecurityError

android - 从不可组合函数中访问可组合函数

kotlin - 是否可以将某些Corda节点与网络中的其他节点隐藏?

c# - 如何将枚举作为方法参数传递?

Android:以编程方式删除或禁用 Samsung Galaxy S2 设备上的锁定屏幕

android - 如何在android中使用FFMPEG修剪视频

android - 返回一个表面上可以为 null 但实际上不能为 null 的变量的值