Skip to content

Kotlin ternary operator example

  • by
kotlin ternary operator example

1. Overview

In this article, we will discuss the Kotlin ternary operator example.

2. Kotlin ternary operator

A ternary operator in Java is a simplified form of the if else statement. The syntax of the ternary operator in Java is.

variable = condition ? expression1 : expression2 

is equivalent to

if (condition) { 
   expression1 
} else {
   expression2
}

The condition in the ternary operator either evaluates to true or false. Based upon the result, it executes a different code. If the condition is true, then the expression1 executes. If the condition is false, then the expression2 executes.

The ternary operator also acts as an expression and returns the result to the left-hand side of the assignment. The If else statement in Java doesn’t behave as an expression.

Coming to Kotlin, there is no ternary operator like in Java. The normal if can behave as an expression. Thus, it eliminates the need for a ternary operator.

3. Kotlin if else one line instead of ternary operator

You can use Kotlin if else in one line as an expression and return a value.

The syntax of if else expression is:

variable = if (condition) expression1 else expression2

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

This is like the ternary operator in Java. If the condition evaluates to true, then the expression1 executes. If it is false, then expression2 executes.

Here, the else branch is mandatory. So if you are using the if as an expression, then add the else branch.

For example, the below code is missing the else branch and so throws the error ‘if’ must have both main and ‘else’ branches if used as an expression.

    val c = if (a > b) 30

4. Kotlin if else expression block

The If else branches can be blocks as below. In such scenarios, the last statement of the branch will be the value of the block and it is returned as the result.

In the below code, the condition is true so the if block executes. The last statement of the block is a. So it returns a as the result and is assigned to the variable max.

val a = 20
val b = 20
val max = if (a > b) {
    print("A")
    a
} else {
    print("B")
    b
}

5. Conclusion

In this article, we discussed the Kotlin ternary operator example.

To sum up, there is no ternary operator in Kotlin so it will not work in Kotlin. Alternatively, you can use the ordinary If statement as a ternary operator in Kotlin.

See our other articles related to Kotlin loop until, for loop with step and kotlin foreach with index example if you are interested.

Leave a Reply

Your email address will not be published. Required fields are marked *