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
>Solution :
Use the run-function. It performs a computation and returns its result.
val string: String = null ?: run {
// do some computations here
"something else"
}