Skip to content

Instantly share code, notes, and snippets.

@naixx
Last active November 7, 2022 15:32
Show Gist options
  • Save naixx/9d94c1498c4d45ffda3a to your computer and use it in GitHub Desktop.
Save naixx/9d94c1498c4d45ffda3a to your computer and use it in GitHub Desktop.
Kotlin ternary operator

Motivation

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