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 :
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.