仅在变量为null时分配变量 [英] assign variable only if it is null
问题描述
在Ruby上有这样的东西:
on Ruby one have something like this:
@var ||= 'value'
基本上,这意味着仅当尚未分配@var
时(例如,如果@var
为nil
),@var
将被分配'value'
basically, it means that @var
will be assigned 'value'
only if @var
is not assigned yet (e.g. if @var
is nil
)
我正在Kotlin上寻找相同的东西,但到目前为止,最接近的东西是Elvis运算符.有那样的东西,我错过了文档吗?
I'm looking for the same on Kotlin, but so far, the closest thing would be the elvis operator. Is there something like that and I missed the documentation?
推荐答案
我能想到的最短的方法确实是使用elvis运算符:
The shortest way I can think of is indeed using the elvis operator:
value = value ?: newValue
如果您经常这样做,则可以选择使用委派的属性 ,仅在null
:
If you do this often, an alternative is to use a delegated property, which only stores the value if its null
:
class Once<T> {
private var value: T? = null
operator fun getValue(thisRef: Any?, property: KProperty<*>): T? {
return value
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
this.value = this.value ?: value
}
}
您现在可以创建一个使用该属性的属性,如下所示:
You can now create a property that uses this like so:
var value by Once<String>()
fun main(args: Array<String>) {
println(value) // 'null'
value = "1"
println(value) // '1'
value = "2"
println(value) // '1'
}
请注意,这不是线程安全的,不允许将其设置回null
.另外,这确实会评估new
表达式,而简单的elvis运算符版本则不会.
Note that this is not thread-safe and does not allow setting back to null
. Also, this does evaluate the new
expression while the simple elvis operator version might not.
这篇关于仅在变量为null时分配变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!