Reputation: 1482
I have the following classes, but myfield
variable in both NumberField
and TextField
cannot compile with:
Var-property type is InputField<String?>, which is not a type of overridden public abstract var inputField: InputField<*> defined in [my project]
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()
}
}
I don't really need to know about the type in FieldComponent
, but I need to have access to myfield
if I have an instance of FieldComponent
Can we make this work? Thank you
Upvotes: 1
Views: 325
Reputation: 266
Make FieldComponent
generic.
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()
}
}
Upvotes: 3