Kotlin如果不是空的
什么是最简洁的方式使用iff var
不是null
?
我能想到的最好的是:
arg?.let { with(it) { }}
您可以使用Kotlin扩展函数apply()
或run()
具体取决于您希望它是否流畅 ( 结束时返回 )或转换 ( 在结束时返回新值 ):
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.with(func: T.() -> Unit): T = this.apply(func) // or returning a new value inline fun T.with(func: T.() -> R): R = this.func()
用法示例:
something?.with { // this is now the non-null arg }
如果你想嵌入在函数中的空检查,也许是一个withNotNull
函数?
// version returning `this` or `null` fluently inline fun T?.withNotNull(func: T.() -> Unit): T? = this?.apply(func) // version returning new value or `null` inline fun T?.withNotNull(thenDo: T.() -> R?): R? = this?.thenDo()
用法示例:
something.withNotNull { // this is now the non-null arg }
也可以看看:
-
Any
相关的function - Kotlin 顶级function
- Kotlin StdLib API参考
看起来像这样的替代将是使用:
arg?.run { }