繁体   English   中英

Kotlin如果不是空的话

[英]Kotlin With If Not Null

with iff一起使用最简洁的方法是什么? var不是null

我能想到的最好的是:

arg?.let { with(it) {

}}

您可以使用科特林扩展函数apply()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()的函数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
}

也可以看看:

看起来像这样的替代方案是使用:

arg?.run {

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM