Kotlin 与 If Not Null

Kotlin With If Not Null

var 不是 null 时,使用 with 最简洁的方法是什么?

我能想到的最好的是:

arg?.let { with(it) {

}}

看起来替代方法是使用:

arg?.run {

}

您可以使用 Kotlin 扩展函数 apply() or run(),具体取决于您是否希望它流畅在最后返回 this ) 或转换在结束时返回一个新值):

apply 的用法:

something?.apply {
    // this is now the non-null arg
} 

和流利的例子:

user?.apply {
   name = "Fred"
   age = 31
}?.updateUserInfo()

使用 run 转换示例:

val companyName = user?.run {
   saveUser()
   fetchUserCompany()
}?.name ?: "unknown company"

或者,如果您不喜欢这种命名方式并且确实想要一个名为 with() 的函数 ,您可以轻松创建自己的可重用函数

// returning the same value fluently
inline fun <T: Any> T.with(func: T.() -> Unit): T = this.apply(func)
// or returning a new value
inline fun <T: Any, R: Any> T.with(func: T.() -> R): R = this.func()

用法示例:

something?.with {
    // this is now the non-null arg
}

如果你想在函数中嵌入 null 检查,也许是 withNotNull 函数?

// version returning `this` or `null` fluently
inline fun <T: Any> T?.withNotNull(func: T.() -> Unit): T? = 
    this?.apply(func)
// version returning new value or `null`
inline fun <T: Any, R: Any> T?.withNotNull(thenDo: T.() -> R?): R? =
    this?.thenDo()

用法示例:

something.withNotNull {
    // this is now the non-null arg
}

另请参阅: