【问题标题】:Kotlin override generic variableKotlin 覆盖泛型变量
【发布时间】:2021-11-06 13:53:16
【问题描述】:

我有以下类,但 NumberFieldTextField 中的 myfield 变量无法编译:

Var-property 类型是 InputField,它不是 [my project] 中定义的被覆盖的 public abstract var inputField: InputField 的类型


interface FieldComponent {
    var myfield: InputField<*>  // <-- what should this be
}

interface InputField<T> {
    fun collectInput(): T
}

class NumberField(): FieldComponent{
    override lateinit var myfield: InputField<Int> // won't compile

    fun doSomething(){
        val x: Int = myfield.collectInput()
    }
}

class TextField(): FieldComponent{
    override lateinit var myfield: InputField<String> // won't compile

    fun doSomething(){
        val x: String = myfield.collectInput()
    }
}

我真的不需要知道FieldComponent 中的类型,但如果我有FieldComponent 的实例,我需要访问myfield 我们可以完成这项工作吗?谢谢

【问题讨论】:

  • myfield 应该是val in FieldComponent,否则覆盖属性时将无法使用子类型
  • 为什么不像 InputField 接口那样使用类型参数?
  • 您是否打算让FieldComponent 的用户替换myfield 的值?我问,因为它被声明为var
  • myfield 中的 FieldComponent 更改为 val 解决问题。谢谢大家。
  • @IR42 考虑将您的评论转换为答案,以便它可以被接受,这样问题就可以“关闭”,其他人可以从中受益并轻松理解这可能是类似问题的可能解决方案;) 谢谢!

标签: kotlin generics


【解决方案1】:

使FieldComponent 通用。

interface FieldComponent<T> {
    var myfield: InputField<T>
}

interface InputField<T> {
    fun collectInput(): T
}

class NumberField(): FieldComponent<Int> {
    override lateinit var myfield: InputField<Int>
    fun doSomething(){
        val x: Int = myfield.collectInput()
    }
}

class TextField(): FieldComponent<String> {
    override lateinit var myfield: InputField<String>
    fun doSomething(){
        val x: String = myfield.collectInput()
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多