Kotlin ternary operator

Kotlin ternary operator



Kotlin is very expressive language, but like Scala it lacks of ternary operator. Currently language provided alternative if looks a bit verbose.

val result = if (myExpression) 1 else 2

Compared to a classical Java or C++ variant

int result = myExpression ? 1 : 2

Unlike Scala, Kotlin allows only fixed names for operators, so we cant fully reproduce classic syntax, but we can have something similar

val result = myExpression % 1 / 2

If you want to use complex boolean expression, you can wrap it in braces

val result = (a == null && b > 5) % 1 / 2

The impact I see here is temporary object creation, probably inline can't help.

class Ternary<T>(val expr: Boolean, val then: T) {
    public fun div(elze: T): T = if (expr) then else elze

public fun <T> Boolean.mod(a: T): Ternary<T> = Ternary(this, a)