Extension functions are really great for making life easier, allowing us to add functionality to types that aren’t our own. One area we can use an extension is for launching Android Activities more easily.

We can build an extension that allows all Activities to be launched via a generic type argument. An optional request code can be passed to the function, which controls whether startActivity or startActivityForResult is used to launch the Activity. By providing an intent builder function, the Intent that is fired can be customised.

inline fun <reified ActivityT : Activity> Activity.startActivity(
    requestCode: Int? = null,
    intentBuilder: Intent.() -> Unit = {}
) {
    val intent = Intent(this, ActivityT::class.java)
        .apply { intentBuilder() }
    if (requestCode == null) {
        startActivity(intent)
    } else {
        startActivityForResult(intent, requestCode)
    }
}

fun startContactCreation(fromActivity: Activity, requestCode: Int) {
    fromActivity.startActivity<ConnectionCreationActivity>(requestCode) {
        putExtra("source", ConnectionCreationSource.CONNECTIONS)
    }
}

Thanks for reading and happy coding! πŸ™