Hello, Is there any standard function with similar...
# getting-started
a
Hello, Is there any standard function with similar behaviour (ifNull extension function)? Or maybe there are some nice idiomatic ways to do that?
m
Just use
let
and
?:
.
Copy code
superHeavyOperation()
    ?.let { -24 + it.length } ?: 42
a
oh yeah, that makes sense. thanks. I slightly over-engineered 🙂
a
I keep saying it, but make sure that your let expression does not return null or the else wil lalso be executed
a
yeah, that's a good point.
m
That's a feature, not a limitation if you ask me 😉
a
Well feature of
let
sure, but if that's not desirable maybe you'll want to use
also
or
apply
Personally I would probably go for
Copy code
when(val it = superHeavyOperation()) {
  null -> 42
  else -> -24 + it.length
}
a
hmm, is that compilable?
a
afaik yes
a
just checked that, yes that the solution I was looking for
i thought it is kind of impossible to put val declaration. so now that is it much more clear and concise
a
I think it is impossible to do the call declaration and treat the when as if/elseif branches, which is a pity