Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elvis operator for computed values

Tags:

kotlin

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

like image 649
Page not found Avatar asked Sep 08 '26 06:09

Page not found


2 Answers

Use the run-function. It performs a computation and returns its result.

val string: String = null ?: run {
    // do some computations here
    "something else"
}
like image 146
marstran Avatar answered Sep 12 '26 17:09

marstran


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()
like image 38
Sweeper Avatar answered Sep 12 '26 16:09

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!