The ternary operator is the only operator that takes 3 operands. It is used to implement conditional statements in a single line. Various programming languages such as Java, JavaScript, C#, etc have ternary operator feature. Its syntax looks like this:
(condition) ? (expression1) : (expression2)
If the condition is true, expression1 is executed otherwise expression2.
Does Kotlin Support Ternary Operator?
Kotlin does not support ternary operator directly. But we can implement it in Kotlin using a one-liner if else. It’s also known as shorthand syntax for writing simple if-else expressions.
Here is an example that demonstrates the implementation of the ternary operator in Kotlin using if else.
fun main() {
val x = 10
val result = if (x > 5) "greater than 5" else "less than or equal to 5"
println(result)
}
Output:
greater than 5
Here is a video that will help you to understand the concept easily. Comment down below for any queries or feedback.