Kotlin Ternary Operator
Kotlin does not have a traditional ternary operator (like the ? :
operator in languages such as Java or C++). Instead, you can use the if
expression, which can be used in a similar way.
The following is the syntax to use if-else as Ternary Operator.
if (condition) value1 else value2
If the condition
is true, the above expression returns value1
, otherwise returns value2
.
And you can assign the returned value to a variable as shown.
x = if (condition) value1 else value2
You can also write code for the if block, and else block, as shown in the following syntax.
val result = if (condition) {
// code to execute if condition is true
value1
} else {
// code to execute if condition is false
value2
}
Example 1: Check if number is ‘Even’ or ‘Odd’
In this example, we shall use “if else” expression as Ternary operator, to assign a string value of ‘Even’ if the given number is an even number, of ‘Odd’ if otherwise.
Kotlin Program
fun main() {
val number = 5
val result = if (number % 2 == 0) "Even" else "Odd"
println(result)
}
Output
Odd
You may change the value in number
and see the output.