Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android Activity static starter method in Kotlin

Tags:

android

kotlin

In java, one can define a starter static method for an Activity. In Android Studio, there is even a "starter" template for it: it would look something like this:

public class MyActivity extends AppCompatActivity {

    private static final String EXTRA_FOO = "foo";

    public static void start(Context caller, String bar){
        Intent intent = new Intent(caller, MyActivity.class);
        intent.putExtra(EXTRA_FOO, bar);
        caller.startActivity(intent);
    }
}

I'm wrapping my head around this same concept in Kotlin and the closest thing I came up with looks like this:

class MyActivity : AppCompatActivity() {

    companion object {
        private val EXTRA_FOO = "foo"

        fun start(caller: Context, bar: String){
            val intent = Intent(caller, MyActivity::class.java)
            intent.putExtra(EXTRA_FOO, bar)
            caller.startActivity(intent)
        }
    }
}

Is there a more concise and elegant way to do this? I can't believe this is the way to go, it looks uglier than in Java. Also, there is no "starter" template for Kotlin.

like image 396
lelloman Avatar asked Oct 18 '22 10:10

lelloman


1 Answers

There are a few approaches you could take. I'm a fan of extension functions:

class MyActivity : AppCompatActivity()

private fun Intent.extraFoo(bar : String) = putExtra("foo", bar)

fun Context.startMyActivity(bar : String) =
    Intent(this, MyActivity::class.java).apply { extraFoo(bar) }.let(this::startActivity)

This creates an extension to Context so that you can call startMyActivity on any Context object.


Here's that same extension function in a more Java-like style, so you can compare it more easily to what you already have:

private val EXTRA_FOO = "foo"

fun Context.startMyActivity(bar : String) {
    val intent = Intent(this, MyActivity::class.java)
    intent.putExtra(EXTRA_FOO, bar)
    startActivity(intent)
}
like image 150
Sam Avatar answered Oct 21 '22 07:10

Sam