Reputation: 12362
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
Reputation: 81539
The nicest way to do it is this:
return when {
condition -> a
else -> b
}
Upvotes: 1
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
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
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