Suppose we have this code:
class QuickExample {
fun function(argument: SomeOtherClass) {
if (argument.mutableProperty != null ) {
doSome
I don't believe there is a really "short" way to achieve it, however you can simply use a conditional within with
or let
:
with(mutableVar) { if (this != null) doSomething(this) else doOtherThing() }
mutableVar.let { if (it != null) doSomething(it) else doOtherThing() }
In fact, "capturing" a mutable value is one of the main use cases of let
.
This is equivalent to your when
statement.
There is always the option you described, assigning it to a variable:
val immutable = mutableVar
if (immutable != null) {
doSomething(immutable)
} else {
doOtherThing()
}
which is always a nice fallback in case e.g. things get too verbose.
There probably isn't really a very nice way to achieve this because only the last lambda argument is allowed to be put outside the ()
, so specifying two wouldn't really fit the syntax of all of the other standard functions.
You could write one if you don't mind that (or if you'll be passing method references instead):
inline fun T?.ifNotNullOrElse(ifNotNullPath: (T) -> R, elsePath: () -> R)
= let { if(it == null) elsePath() else ifNotNullPath(it) }
...
val a: Int? = null
a.ifNotNullOrElse({ println("not null") }, { println("null") })
Note that I would personally not do this, because none of these custom constructs are very pleasant to read. IMO: stick with let
/run
and fall back to if
-else
when necessary.