I develop an app in Kotlin that has many Activities
. Most of the navigation is just basic, starting the new activity, not passing anything to the intent. For a few groups of Activities I might pass flags, which is also repetitive throughout my project (e.g. 5 Activities that set intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
). So if I could find a way to make that just one implementation would make things a little nicer.
To make things easier and a little neater, I have created companion objects for the Activities
that hold the following function:
class MyActivity: AppCompatActivity() {
companion object {
fun startActivity(context: Context) {
context.startActivity(
Intent(context, MyActivity::class.java)
)
}
}
...
Other classes can simply call MyActivity.startActivity(context)
.
The function is pretty basic and the only difference between the implementation in different Activities is obviously the MyActivity::class.java
-part. So id like to know if its possible to declare this function only ONCE and somehow use it within multiple companion objects for the different activities.
Now, I understand I could do something like this:
I define an object that has a function with a generic type and set it up like this:
object MyObject {
inline fun <reified T: AppCompatActivity>startActivity(context: Context) {
context.startActivity(
Intent(context, T::class.java)
)
}
}
class MyActivity() : AppCompatActivity() {
companion object {
fun start(context: Context) = MyObject.startActivity<MyActivity>(context)
}
}
But this still seems a little hacky. What I'm looking for is something like inheritance or an implemented version of an interface to simply add to my companion object. Something like:
companion object : MyObject<MyActivity>
// Assuming I can somehow put the generic parameter into the object declaration instead of the function or do something similar
or
companion object {
import MyObject.startActivity<MyActivity>
}
The first option would be especially useful, as it would automatically set up multiple functions of MyObject
for MyActivity
. Is something like this even possible?