首页 > 解决方案 > 在 kotlin 中比较创建函数的两种方法

问题描述

我有这个功能片段

fun getNewIntent(context: Context, following: Boolean, userId: String): Intent {
    val intent = Intent(context, UsersActivity::class.java)
    intent.putExtra(FOLLOW, following)
    intent.putExtra(USER, userId)
    return intent
}

也可以这样写

fun getNewIntent(context: Context, following: Boolean, userId: String): Intent =
        Intent(context, UsersActivity::class.java).also {
            it.putExtra(FOLLOW, following)
            it.putExtra(USER, userId)
        }

并且在一个例子中它只有1个参数

fun getNewIntent(context: Context, userId: String): Intent =
        Intent(context, UsersActivity::class.java).apply { putExtra(USER, userId) }

哪一个更好?为什么?

标签: androidkotlin

解决方案


它们基本上是等价的。我会选择对你和/或你的团队来说最易读的东西。

如果函数中的功能足够清楚,我个人喜欢直接分配。通常情况下,如果它是单行的,或者如果初始化之后是类似的东西.apply(所以基本上只是相对较短)。对于您的功能,我实际上会介绍以下内容:

inline fun <reified T> newIntent(context: Context, applyToIntent : Intent.() -> Unit = {}) = Intent(context, T::class.java).apply(applyToIntent)

然后可重复用于多个活动。用法可以很简单:

newIntent<UsersActivity>(context) {
  putExtra(FOLLOW, following)
  putExtra(USER, userId)
}

或者如果你真的需要你当前的功能(虽然我没有看到它的真正原因),它仍然很简单:

fun getNewIntent(context: Context, following: Boolean, userId: String) = newIntent<UsersActivity>(context) {
    putExtra(FOLLOW, following)
    putExtra(USER, userId)
}

推荐阅读