Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way to assign only if the right side is not null?

In Kotlin, I want to do an assignment only if another variable is not null (otherwise, no op). I can think of two succinct ways:

fun main(args: Array<String>) {
    var x: Int? = null
    var n = 0

    // ... do something ...

    x?.let { n = it }  // method 1
    n = x ?: n         // method 2
}

However, they don't feel succinct enough, given the frequency I have to do them. The first method seems an overkill. The second method is nagging in requiring an expression after ?:.

I suspect there must be a better way, something like n =? x? Or n = x?? Is there?

like image 837
Nick Lee Avatar asked Dec 24 '17 07:12

Nick Lee


1 Answers

Try infix to 'simulate custom infix operations'

// define this
infix fun <T > T.assignFromNotNull(right: T): T = right ?: this

///////////////////////////////////////////////////////////
// Demo using

// Now, Kotlin infix-style
fooA assignFromNotNull fooB
barA assignFromNotNull barB
bazA assignFromNotNull bazB

// Old code, Java if-style
if (fooB != null) {
    fooA = fooB;
}
if (barB != null) {
    barA = barB;
}
if (bazB != null) {
    bazA = bazB
}
like image 174
Raymond Avatar answered Sep 22 '22 13:09

Raymond