android - 在 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) }
哪一个更好?为什么?
解决方案
它们基本上是等价的。我会选择对你和/或你的团队来说最易读的东西。
如果函数中的功能足够清楚,我个人喜欢直接分配。通常情况下,如果它是单行的,或者如果初始化之后是类似的东西.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)
}
推荐阅读
- android - Android gradle 看不到主机名
- java - 使用单独的锁保证锁定每个值
- broadcast - Dask scatter 广播列表
- ios - 使用 subdivisionLevel 平滑 SCNGeometry
- node.js - 由于“grpc”,无法推送到 Heroku
- javascript - 如何从 iFrame 内部滚动到 iFrame 顶部
- jasper-reports - 如何设置 REPORT_TIME_ZONE 参数的值?
- reactjs - React-Redux 组件状态
- android - AGPBI: {"kind":"error","text":"程序类型已经存在:org.openqa.selenium.WebDriver$ImeHandler","sources":[{}],"tool":"D8"}
- twitter-bootstrap - Boostrap 导航栏切换器不可见