In Kotlin we can use the Elvis operator ?: like this:
val string: String = null ?: "something else"
But what if "something else" is the result of a computation, like
val string: String = null ?: {
// do some comutations here
"something else"
}
This won't compile as the right hand side of ?: is a function () => String and not String.
I have a feeling that I need to use one of the function takeIf, takeUnless etc. but I don't get it.
Thanks
Use the run-function. It performs a computation and returns its result.
val string: String = null ?: run {
// do some computations here
"something else"
}
You can use run:
val string = something ?: run {
// you can write multiple lines of code here,
// to compute a final result
val x = foo()
val y = bar(x)
baz(x, y)
}
Alternatively, if this doesn't need to be inline, just extract a function:
val string = something ?: computeValue()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With