Equivalent to the conditional or ternary operator in Kotlin

Asked

Viewed 3,000 times

8

Below I am logging on the monitor of Android Studio in JAVA a short phrase using conditional or ternary operator (?)en. Look at:

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

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

4 answers

10


Kotlin has no ternary operator but a if can return a value (i.e., it is treated as an expression) and function in the same way, with the detail is you are bound to have a block else. As stated in documentation:

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.

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

8

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

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

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

There are also other described implementations in that question of SOEN.

7

In Kotlin these structures are used as expressions tb:

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

7

Just to complement, in version 1.1 came the extension takeIf, that along with Lvis Perator (?:) may contribute in that event.

Your expression would be:

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

It’s a little different than usual if you’re tired of the standard if/Else.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.