Assign a variable only if it is zero
there is something like this in Ruby:
@var ||= 'value'
basically, it means it @var
will 'value'
only be assigned if @var
not already assigned (e.g. if @var
there is nil
)
I'm looking for the same in Kotlin, but so far the closest will be Elvis's operator. Is there something similar and I missed the documentation?
source to share
The shortest path I can think of is actually using the elvis operator:
value = value ?: newValue
If you do this often, an alternative is to use a delegated property , which only retains the value if it is 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
}
}
Now you can create a property that uses it like this:
var value by Once<String>()
fun main(args: Array<String>) {
println(value) // 'null'
value = "1"
println(value) // '1'
value = "2"
println(value) // '1'
}
Note that this is not thread safe and does not allow backtracking null
. Also, this evaluates an expression new
, while a simple version of the elvis operator cannot.
source to share