【发布时间】:2021-11-06 13:53:16
【问题描述】:
我有以下类,但 NumberField 和 TextField 中的 myfield 变量无法编译:
Var-property 类型是 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应该是valinFieldComponent,否则覆盖属性时将无法使用子类型 -
为什么不像
InputField接口那样使用类型参数? -
您是否打算让
FieldComponent的用户替换myfield的值?我问,因为它被声明为var。 -
将
myfield中的FieldComponent更改为 val 解决问题。谢谢大家。 -
@IR42 考虑将您的评论转换为答案,以便它可以被接受,这样问题就可以“关闭”,其他人可以从中受益并轻松理解这可能是类似问题的可能解决方案;) 谢谢!