Reputation: 1628
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
Reputation: 14907
I think your problem is that let
can also return a value, so the second run
block executes:
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
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