lulumeya
lulumeya

Reputation: 1628

else block for multiple ? expression in kotlin

I need else block for code below

one?.two?.three?.four?.let { } // need else block here

Is there any expression could be used this case?

Upvotes: 1

Views: 577

Answers (2)

Salem
Salem

Reputation: 14907

I think your problem is that let can also return a value, so the second run block executes:

  • if the original value is null
  • if the return value is null (not what you want!)

To avoid this happening, you need to return Unit from the let block:

one?.two?.three?.four?.let {
    doStuff()
    Unit
} ?: run {
    doOtherStuff()
}

You could also use a typical if statement, without ?.:

one?.two?.three?.four.let {
                  // ^ no ?.
    if (it == null) doStuff() else doOtherStuff()
}

Upvotes: 1

Yaroslav Samardak
Yaroslav Samardak

Reputation: 59

You can use elvis operator.

Like this:

one?.two?.three?.four?.let {
    // if not null
} ?: run { 
    // if null
}

If you want call block for null element, then you can use infix

infix fun Any?.ifNull(block: () -> Unit) {
    if (this == null) block()
}

one?.two?.three?.four ifNull {
    // Do anything
}

Upvotes: 1

Related Questions