Skip to content

Instantly share code, notes, and snippets.

Last active Jan 16, 2018
What would you like to do?
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 impcat I see here is temporaty object creation, probably inline can't help.

class Ternary<T>(private val expr: Boolean, private val then: T) {
infix operator fun div(elze: T): T = if (expr) then else elze
infix operator fun <T> Boolean.rem(a: T): Ternary<T> = Ternary(this, a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment