Kotlin Ternary Conditional Operator

Drew Noakes Source

What is the equivalent of this expression in Kotlin?

a ? b : c

This is not a valid code in Kotlin.

javaif-statementkotlinternary-operator

Answers

answered 5 years ago Drew Noakes #1

In Kotlin, if statements are expressions. So the following code is equivalent:

if (a) b else c

The distinction between expression and statement is important here. In Java/C#/JavaScript, if forms a statement, meaning that it does not resolve to a value. More concretely, you can't assign it to a variable.

// Valid Kotlin, but invalid Java/C#/JavaScript
var v = if (a) b else c

If you're coming from a language where if is a statement, this might seem unnatural but that feeling should soon subside.

answered 3 years ago ruX #2

For myself I use following extension functions:

fun T?.or<T>(default: T): T = if (this == null) default else this 
fun T?.or<T>(compute: () -> T): T = if (this == null) compute() else this

First one will return provided default value in case object equals null. Second will evaluate expression provided in lambda in the same case.

Usage:

1) e?.getMessage().or("unknown")
2) obj?.lastMessage?.timestamp.or { Date() }

Personally for me code above more readable than if construction inlining

answered 2 years ago Li Ying #3

Take a look at the docs:

In Kotlin, if is an expression, i.e. it returns a value. Therefore there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.

answered 1 year ago deviant #4

You could define your own Boolean extension function that returns null when the Boolean is false to provide a structure similar to the ternary operator:

infix fun <T> Boolean.then(param: T): T? = if (this) param else null

This would make an a ? b : c expression translate to a then b ?: c, like so:

println(condition then "yes" ?: "no")

Update: But to do some more Java-like conditional switch you will need something like that

infix fun <T> Boolean.then(param: () -> T): T? = if (this) param() else null

println(condition then { "yes" } ?: "no") pay attention on the lambda. its content calculation should be postponed until we make sure condition is true

This one looks clumsy, that is why there is high demanded request exist to port Java ternary operator into Kotlin

answered 9 months ago Guruprasath #5

when replaces the switch operator of C-like languages. In the simplest form it looks like this

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> {
        print("x is neither 1 nor 2")
    }
}

answered 9 months ago Kris Roofe #6

In Kotlin, if is an expression, i.e. it returns a value. Therefore there is no ternary operator (condition ? then : else), because ordinary if works fine in this role. manual source from here

// Traditional usage 
var max = a 
if (a < b) max = b

// With else 
var max: Int
if (a > b) {
    max = a
} else {
    max = b
}

// As expression 
val max = if (a > b) a else b

answered 9 months ago Minami #7

as Drew Noakes quoted, kotlin use if statement as expression, so Ternary Conditional Operator is not necessary anymore,

but with the extension function and infix overloading, you could implement that yourself, here is an example

infix fun <T> Boolean.then(value: T?) = TernaryExpression(this, value)

class TernaryExpression<out T>(val flag: Boolean, val truly: T?) {
    infix fun <T> or(falsy: T?) = if (flag) truly else falsy
}

then use it like this

val grade = 90
val clazz = (grade > 80) then "A" or "B"

answered 8 months ago HM Nayem #8

There is no ternary operator in Kotlin. It seems problematic at the first glance. But think we can do it with inline if else statement because this is expression here. Simply we have to do -

var number = if(n>0) "Positive" else "Negetive"

Here we can else if block too as many as we need. Like-

var number = if(n>0) "Positive" else if(n<0) "Negative" else "Zero"

So this line is so simple and much readable than ternary operator. when we use more than one ternary operator in java it seems horrible. But here we have a clear syntax. even we can write it in multiple line too.

answered 8 months ago Vadzim #9

Some corner cases not mentioned in other answers.

Since appearance of takeIf in Kotlin 1.1 the ternary operator a ? b : c can also be expressed like this:

b.takeIf { a } ?: c

This becomes even shorter in case c is null:

b.takeIf { a }

Also note that typical in Java world null checks like value != null ? value : defaultValue translate in ideomatic Kotlin to just value ?: defaultValue.

Similar a != null ? b : c can be translated to a?.let { b } ?: c.

answered 8 months ago doubleThunder #10

Java

int temp = a ? b : c;

Equivalent to Kotlin:

var temp = if (a) b else c

answered 7 months ago Grzegorz Piwowarek #11

Another interesting approach would be to use when:

when(a) {
  true -> b
  false -> b
}

Can be quite handy in some more complex scenarios. And honestly, it's more readable for me than if ... else ...

answered 7 months ago romiope #12

There is no ternary operator in kotlin, as the if else block returns value

so, you can do: val max = if (a > b) a else b instead of java's max = (a > b) ? b : c

We can also use when construction, it also return value:

val max = when(a > b) {
    true -> a
    false -> b
}

here is link for documentation https://kotlinlang.org/docs/reference/control-flow.html

answered 5 months ago Vinod Pattanshetti #13

Another short approach to use

val value : String = "Kotlin"

value ?: ""

Here kotlin itself checks null value and if it is null then it passes empty string value.

answered 5 months ago Rajesh Dalsaniya #14

You can do it many way in Kotlin

  1. Using if

    if(a) b else c
    
  2. Using when

    when (a) { 
        true -> print("value b") 
        false -> print("value c") 
        else -> {  
            print("default return in any other case") 
        } 
    }
    
  3. Null Safety

    val a = b ?: c
    

answered 4 months ago s1m0nw1 #15

Statements -> Expressions

In Kotlin, many control statements including if, when or even try can be used as expressions. This means, it has a result and can be assigned to a variable, returned from a function and so on.

No need for ternary operator

Having said that, Kotlin does not need the ternary operator.

if (a) b else c is what you can use instead of the Java expression a ? b : c.

IMO, the latter is less readable since everybody knows what ifelse does, whereas? : is quite inconvenient. So I agree that a ternary operator has no right to exist in Kotlin.

Other Alternatives

when

You might also see a lot when constructs whenever conditions are checked in Kotlin. It's also a way to express if-else cascades in an alternative way. The following corresponds to your example.

when(a) {
    true -> b
    false -> b
}

Extensions

As many good examples (https://stackoverflow.com/a/39687177/8073652) in the other answers show, extensions can also be a way to go.

answered 3 months ago Gowtham Subramaniam #16

In Kotlin, there is no ternary operator.

In Kotlin, if is an expression, i.e. it returns a value.

Therefore there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.

Equivalent in Kotlin

var a = if (a) b else c

Reference document: https://kotlinlang.org/docs/reference/control-flow.html

answered 3 months ago Nicolas Cornette #17

With the following infix functions I can cover many common use cases pretty much the same way it can be done in Python :

class TestKotlinTernaryConditionalOperator {

    @Test
    fun testAndOrInfixFunctions() {
        Assertions.assertThat(true and "yes" or "no").isEqualTo("yes")
        Assertions.assertThat(false and "yes" or "no").isEqualTo("no")

        Assertions.assertThat("A" and "yes" or "no").isEqualTo("yes")
        Assertions.assertThat("" and "yes" or "no").isEqualTo("no")

        Assertions.assertThat(1 and "yes" or "no").isEqualTo("yes")
        Assertions.assertThat(0 and "yes" or "no").isEqualTo("no")

        Assertions.assertThat(Date() and "yes" or "no").isEqualTo("yes")
        @Suppress("CAST_NEVER_SUCCEEDS")
        Assertions.assertThat(null as Date? and "yes" or "no").isEqualTo("no")
    }
}

infix fun <E> Boolean?.and(other: E?): E? = if (this == true) other else null
infix fun <E> CharSequence?.and(other: E?): E? = if (!(this ?: "").isEmpty()) other else null
infix fun <E> Number?.and(other: E?): E? = if (this?.toInt() ?: 0 != 0) other else null
infix fun <E> Any?.and(other: E?): E? = if (this != null) other else null
infix fun <E> E?.or(other: E?): E? = this ?: other

answered 2 months ago Gulzar Bhat #18

You can use if expression for this in Kotlin. In Kotlin if is an expression with a result value. So in Kotlin we can write

fun max(a: Int, b: Int) = if (a > b) a else b

and in Java we can achieve the same but with larger code

int max(int a, int b) {
return a > b ? a : b
}

answered 3 weeks ago Juan Mendez #19

When working with apply(), let seems very handy when dealing with ternary operations, as it is more elegant and give you room

enter image description here

answered 2 weeks ago pranalli #20

There is no ternary operation in Kotlin, but there are some fun ways to work around that. As others have pointed out, a direct translation into Kotlin would look like this:

val x = if (condition) result1 else result2

But, personally, I think that can get a bit cluttered and hard to read. There are some other options built into the library. You can use takeIf {} with an elvis operator:

val x = result1.takeIf { condition } ?: result2

What is happening there is that the takeIf { } command returns either your result1 or null, and the elvis operator handles the null option. There are some additional options, takeUnless { }, for example:

val x = result1.takeUnless { condition } ?: result2

The language is clear, you know what that's doing.

If it's a commonly used condition, you could also do something fun like use an inline extension method. Let's assume we want to track a game score as an Int, for example, and we want to always return 0 if a given condition is not met:

inline fun Int.zeroIfFalse(func: () -> Boolean) : Int = if (!func.invoke()) 0 else this     

Ok, that seems ugly. But consider how it looks when it is used:

var score = 0
val twoPointer = 2
val threePointer = 3

score += twoPointer.zeroIfFalse { scoreCondition } 
score += threePointer.zeroIfFalse { scoreCondition } 

As you can see, Kotlin offers a lot of flexibility in how you choose to express your code. There are countless variations of my examples and probably ways I haven't even discovered yet. I hope this helps!

answered 2 weeks ago Ranjith Rayapati #21

As per Kotlin documentation for myself, I use the following code:

 val max = if (a > b) a else b

And:

when (x) {
  1 -> print("x == 1")
  2 -> print("x == 2")
  else -> { // Note the block
      print("x is neither 1 nor 2")
  }
}

If you want to know more information check this link https://kotlinlang.org/docs/reference/control-flow.html

comments powered by Disqus