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


#1

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?


#2

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.


#3

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?


#4

Use val instead of var?


#5

Generics?


#6

Resolved:
override lateinit var myButton: MyButton

val myButton: HasProgress