Why companion object for newStartIntent in Android+Kotlin?

Viewed 494

I have seen quite a few examples in Kotlin where an activity class has a companion object to encapsulate the creation of a start intent like the following. It seems particularly Java inspired.

class HomeActivity : AppCompatActivity() {

    companion object {

        fun newStartIntent(context: Context): Intent {
            val intent = Intent(context, HomeActivity::class.java)
            return intent
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.setContentView(R.layout.activity_home)
        // ...
    }

    // ...
}

Since Kotlin has top level functions, why not skip the companion object and just have a top level function?

fun newHomeActivityStartIntent(context: Context): Intent {
    val intent = Intent(context, HomeActivity::class.java)
    return intent
}

class HomeActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.setContentView(R.layout.activity_home)
        // ...
    }

    // ...
}
1 Answers

There is nothing wrong in your approach actually. I thought of a few reasons why I would choose a companion object over top-level functions:

  1. Top-level functions visible for everyone, thus every time you start typing new... you will get a list of partially irrelevant results;
  2. Companion objects can hold private values that you would not like to make open to the public and keep them visible only within your class but still make them static. Maybe there are some arguments that are calculated under this function invocation and passed with intent, and you would like to hide these calculations or arguments keys;
  3. This is not your case but still relevant: using companion object you can make all constructors private and control all arguments passed to object initialization. This is how Singleton can be created in Kotlin;
  4. Opinionated For me personally it makes things look tidy. I usually extract only simple and relatively vastly used functions. Like Date conversion functions, or math function calculations.

It is a matter of style. Just pick one and be consistent!

Related