Equivalent to the conditional or ternary operator in Kotlin

7

Below I'm logging into the Android Studio in JAVA a short phrase using conditional or ternary operator ( ?) in . See:

Log.wtf(GOT, (valirianSteel == 0 && glassOfDragon==0)  ? "Run!" : "Run too!");

What would be equivalent to the conditional or ternary operator in Kotlin?

    
asked by anonymous 10.08.2017 / 17:05

4 answers

9

Kotlin does not have a ternary operator but a if can return a value (ie it is treated as an expression) and works the same way, with detail is you are required to have a block else . As stated in documentation :

  

In Kotlin, if it 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.

If any of the blocks has more than one statement the last will be considered the return.

    
10.08.2017 / 17:08
8

There are no ternary expressions proper in Kotlin (until the tual version).

I think the closest to the ternary in Kotlin would be this:

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

There are also other implementations described in this SOEN question .

    
10.08.2017 / 17:07
7

In Kotlin these structures are used as expressions tb:

Log.wtf(GOT, if(valirianSteel == 0 && glassOfDragon==0) "Run!" else "Run too!");
    
10.08.2017 / 17:08
7

Just to complement, in version 1.1 came the takeIf extension, which together with elvis operator ( ?: ) can contribute in this case.

Your expression would look like:

Log.wtf(GOT, "Run!".takeIf { valirianSteel == 0 && glassOfDragon==0 } ?: "Run too!")

It's a bit different from the usual case if you're tired of the default if / else.

    
10.08.2017 / 17:19