Add smart cast of `override var` from interface `var`

Code:

    class AnyActivity : IAnyActivityView {
    override lateinit var myButton: MyButton
}

class AnyActivityPresenter {

    var view:IAnyActivityView = AnyActivity()

    fun makeFunc() {
        view.myButton.showProgress()
        view.myButton.hideProgress()
    }
}


class MyButton() : HasProgress {
    override fun showProgress() {
    }

    override fun hideProgress() {
    }
}

interface HasProgress {
    fun showProgress()
    fun hideProgress()
}

    interface IAnyActivityView {
        var myButton: HasProgress
    }

Why the error occurs
Type of ‘myButton’ doesn’t match the type of the overridden var-property ‘public abstract var myButton: HasProgress defined in IAnyActivityView’ and override lateinit var myButton: MyButton doesn’t smart cast to HasProgress?

Why the error occurs
Type of ‘ myButton ’ doesn’t match the type of the overridden var-property ‘ public abstract var myButton: HasProgress defined in IAnyActivityView

Because it would override the property’s setter with a more specific type. While this is ok for getters, it is not allowed for setters. More generally: you cannot override any function with a more specific argument type. If you are coming from Java, it is the same there.

Oh…Yes you are right. So can you tell me what should I write to get myButton as HasProgress , without creation any new method in AnyActivity?

Use val instead of var?

2 Likes

Generics?

1 Like

Resolved:
override lateinit var myButton: MyButton

val myButton: HasProgress

1 Like