We all have heard about Ternary Operator. A ternary operator is a simple inline compact way to write conditional statements. It allows us to implement condition-based output if the condition is True then the first defined value and on condition false return the second value system. But Kotlin does not support traditional ternary operators which we have seen in all the programming languages. Instead, we can do the same functionality in Kotlin using If-Else.
How to Use Ternary Operator in Kotlin: Simplified Guide with Examples
What does a traditional ternary operator look like?
1 2 3 |
// In Java int max = (a > b) ? a : b; |
Ternary Operator in Kotlin.
1 2 3 4 |
// In Kotlin int max = if (a > b) a else b |
Ternary operator equivalent in Kotlin.
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main() { val a = 10 val b = 20 // Kotlin's equivalent to ternary operator val max = if (a > b) a else b println("The maximum value is: $max") } // Output The maximum value is: 20 |
Ternary operator code example for checking number is even or odd in Kotlin.
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main() { val number = 5 // Kotlin equivalent to ternary operator for checking even or odd val result = if (number % 2 == 0) "Even" else "Odd" println("$number is $result") } // Output 5 is Odd |
Conclusion:
Although Kotlin does not have the old traditional ternary operator, the inline If-Else does the same job. It is a neat and clean way to write single-line conditional statements. So keep practice the new ways. Happy coding.