Kotlin如果不是空的话

Eli*_*zer 8 null kotlin kotlin-null-safety

使用withiff a 最简洁的方法var是什么null

我能想到的最好的是:

arg?.let { with(it) {

}}
Run Code Online (Sandbox Code Playgroud)

Jay*_*ard 18

您可以使用科特林扩展函数apply()run()取决于你是否希望它是流利(返回this时结束)或转换(返回月底新值):

用途apply:

something?.apply {
    // this is now the non-null arg
} 
Run Code Online (Sandbox Code Playgroud)

流畅的例子:

user?.apply {
   name = "Fred"
   age = 31
}?.updateUserInfo()
Run Code Online (Sandbox Code Playgroud)

转换示例使用run:

val companyName = user?.run {
   saveUser()
   fetchUserCompany()
}?.name ?: "unknown company"
Run Code Online (Sandbox Code Playgroud)

或者,如果您不喜欢这个命名并且真的想要一个名为的函数,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()
Run Code Online (Sandbox Code Playgroud)

用法示例:

something?.with {
    // this is now the non-null arg
}
Run Code Online (Sandbox Code Playgroud)

如果你想在函数中嵌入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()
Run Code Online (Sandbox Code Playgroud)

用法示例:

something.withNotNull {
    // this is now the non-null arg
}
Run Code Online (Sandbox Code Playgroud)

也可以看看: