Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Elvis operator for computed values

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading