user674669
user674669

Reputation: 12362

Is there an kotlin equivalent of ?: java operator?

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;

Upvotes: 3

Views: 2152

Answers (4)

EpicPandaForce
EpicPandaForce

Reputation: 81539

The nicest way to do it is this:

return when {
    condition -> a 
    else -> b
} 

Upvotes: 1

Keisha Josephs PhD
Keisha Josephs PhD

Reputation: 31

The Kotlin equivalent is:

if (a) b else c

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

Upvotes: 2

Karol Dowbecki
Karol Dowbecki

Reputation: 44952

? : 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.

Upvotes: 2

IR42
IR42

Reputation: 9682

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

return if (condition) a else b

Upvotes: 3

Related Questions