A common pattern for the creation of new activities or fragments is to create static factory methods to start an activity, or to create an intent, or to create a new instance of Fragment. When using Kotlin, we can accomplish this using a companion object, which is shown in the following code block with the definition of Factory:
companion object Factory {
const val EXTRA_ID = "extra_id"
@JvmStatic
fun createIntent(context: Context, id: String) =
Intent(context, DetailsActivity::class.java).apply {
putExtra(EXTRA_ID, id)
}
}
Additionally, you could use a top-level function or extension function to achieve similar behavior, as follows:
fun createDetailsIntent(context: Context, id: String) =
Intent(context, DetailsActivity::class.java).apply {
putExtra(DetailsActivity.EXTRA_ID, id)
}
fun Context.createDetailsIntent(id: String) =
Intent(this, DetailsActivity::class.java).apply {
putExtra(DetailsActivity.EXTRA_ID, id)
}
One possible drawback of using a top-level function is that it occupies the global namespace. If you're adding enough functions, it may become difficult for the IDE to autocomplete the function you're looking for. If this is the case for your project, using companion objects to scope your functions is likely the better choice.