🚙 · If expression

1 min read · Updated on by

Read on to find out how if/else acts as a replacement for the ternary operator in Kotlin.

There is no ternary operator (i.e. <condition> ? <then> : <else>) in Kotlin. Instead, if/else may be used as an expression:


//sampleStart
fun max(a: Int, b: Int) = if (a > b) a else b // 1.
fun main() {
    println(max(99, -42))
}
//sampleEnd
  1. if is an expression here — it returns a value. You can wrap each branch in { } if you need it to contain multiple statements.

This is actually much more powerful than the ternary operator, because you can also use else if branches:


//sampleStart
fun sign(x: Int) = if(x < 0) -1 else if(x == 0) 0 else 1
fun main() {
    println(sign(-5))
}
//sampleEnd

In Java, you would need to nest the ternary operator, which quickly gets out of hand:


//sampleStart
Integer sign(final Integer x) {
    return x > 0 ? 1 : (x < 0 ? -1 : 0);
}
//sampleEnd

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

The Kotlin Primer