Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there any way to cast a Context to an Activity directly inside the constructor with Kotlin?

Is there any way to cast a Context to an Activity directly inside the constructor?

Something like that :

class Hud(mainActivity: MainActivity, attrs: AttributeSet?) : SurfaceView(mainActivity, attrs) {

    fun draw() {
        mainActivity.foo()
        ...
    }

}

In order to avoid casting it in every methods :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Hud(context: Context, attrs: AttributeSet?) : SurfaceView(context, attrs) {

    fun draw() {
        val mainActivity = context as MainActivity
        mainAcitivity.foo()
        ...
    }

}

>Solution :

You can do something like this:

class Hud(private val activity: MainActivity) {
    constructor(context: Context) : this(context as MainActivity)
}

Please note that it is generally a bad idea to store an activity instead of the context object itself because then you are tightly coupling your Hud Class with your activity which can cause all sorts of problems.

Please consider changing the design so that these classes are not tightly coupled.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading