1

Reluctant kotlin newbie here.

Is there an kotlin equivalent of ?: java operator?

I tried searching on google. Most results talk about ?: (elvis operator) in kotlin.

Looking for a way to write this in kotlin:

//java example
//return condition ? a : b;
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
user674669
  • 10,681
  • 15
  • 72
  • 105
  • 3
    Does this answer your question? [Kotlin Ternary Conditional Operator](https://stackoverflow.com/questions/16336500/kotlin-ternary-conditional-operator) – ShadowRanger Feb 19 '20 at 17:01

4 Answers4

3

kotlin doesn't have ternary operator, but you can use if, when, try catch as expression

return if (condition) a else b
IR42
  • 8,587
  • 2
  • 23
  • 34
  • In Kotlin, `if (…) … else …` effectively _is_ a ternary operator: it takes three expressions, and returns a value.  It may not _look_ like most other operators, but it's doing exactly the same as the Java/C-style `… ? … : …`.  (Which is why Kotlin doesn't need the latter.) – gidds Feb 19 '20 at 17:47
2

? : is a tenary operator which is currently not present in Kotlin. There are few discussions on adding this operator to the language e.g. KT-5823 Support ternary conditional operator 'foo ? a : b' .

The usual suggestion is to use an if statement as replacement.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
2

The Kotlin equivalent is:

if (a) b else c

That's the closest to the Java that you can get at this point.

1

The nicest way to do it is this:

return when {
    condition -> a 
    else -> b
} 
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • Why would this be the "nicest"? Using `if (a) b else c` seems the obvious choice. – al3c Feb 19 '20 at 17:45
  • Because `b` is equally important to `a`, and are on the same level of horizontal positioning, thus making code more readable. It is also easier to modify, etc. – EpicPandaForce Feb 19 '20 at 23:35