1

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

5
  • 2
    myfield should be val in FieldComponent, otherwise you will not be able to use the subtypes when overriding the property Commented Nov 5, 2021 at 7:15
  • 1
    Why not use a type parameter like you did with the InputField interface? Commented Nov 5, 2021 at 7:25
  • 1
    Do you intend to let users of FieldComponent replace the value of myfield? I ask, because it was declared as var. Commented Nov 5, 2021 at 8:21
  • Changing myfield in FieldComponent to val solve the problem. Thank you all. Commented Nov 5, 2021 at 16:27
  • 1
    @IR42 consider converting your comment into an answer so that it can be accepted so that the question can be ”closed” and others can benefit from it and easily understand which could be a possible solution for similar questions ;) Thanks! Commented Nov 5, 2021 at 20:30

1 Answer 1

3

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()
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.