assign variable only if it is null

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.

Leave a Comment

tech