on Ruby one have something like this:
@var ||= 'value'
basically, it means that @var
will be assigned 'value'
only if @var
is not assigned yet (e.g. if @var
is nil
)
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?
To set the value of a variable is it's equal to null , use the nullish coalescing operator, e.g. myVar = myVar ?? 'new value' . The nullish coalescing operator returns the right-hand side operand if the left-hand side evaluates to null or undefined , otherwise it returns the left-hand side operand.
AndroidMobile DevelopmentApps/ApplicationsKotlin. In Kotlin, "!!" is an operator that is known as the double-bang operator. This operator is also known as "not-null assertion operator". This operator is used to convert any value to a non-NULL type value and it throws an exception if the corresponding value is NULL.
Nullable and Non-Nullable Types in Kotlin – Kotlin type system has distinguish two types of references that can hold null (nullable references) and those that can not (non-null references). A variable of type String can not hold null. If we try to assign null to the variable, it gives compiler error.
The shortest way I can think of is indeed using the elvis operator:
value = value ?: newValue
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'
}
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.
Other way we could do it is by using ifEmpty
..
From the docs: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/if-empty.html
Usage:
val empty = ""
val emptyOrNull: String? = empty.ifEmpty { null }
println(emptyOrNull) // null
val emptyOrDefault = empty.ifEmpty { "default" }
println(emptyOrDefault) // default
val nonEmpty = "abc"
val sameString = nonEmpty.ifEmpty { "def" }
println(sameString) // abc
EDIT:
Seems like this does not work if the initial value is NULL
and only for strings..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With