• Post author:
  • Post category:Kotlin
  • Post last modified:May 9, 2024
  • Reading time:8 mins read

Using the Ternary conditional operator or similar in Kotlin? The ternary operator(e.g., condition ? true_value : false_value) is a conditional operator present in most of the modern-day programming languages like Java, C e.t.c to shorten the expressions of conditional statements.

Advertisements

1. Does Kotlin have a Ternary Conditional Operator?

Kotlin doesn’t have the ternary conditional operator, instead, Kotlin encourages the use of if expressions for achieving the same functionality.

Though the usage of the ternary operator makes the code more clean, elegant, and readable, the Kotlin team decided that the “if else” statement is more readable than ternary operator hence, they decided not to include the ternary conditional operator in the language. However, Kotlin provides us with several alternative methods to achieve similar results. In this article, we will explore how to do so. 

2. Use if-else Statement As Kotlin Ternary Conditional Operator

One of the most common ways to perform conditional operations in Kotlin is to use the “if else” statement. This can perform exactly the same as what the ternary conditional operator offers. The expression has one of multiple if and else expressions with each expression containing the block of codes present which will execute if the condition is met. 


// Example of if statement similar to ternary conditional operator
fun main() {
    val condition = true // Change this condition to true or false
    val ans = if (condition) "yes" else "no"
    println("The result is "+ ans)
}

Yields below output. In the above code, we have created a main function which is our driver code. We have created a variable named condition and we kept its value to be “true”. Next, we used the if-else statement which sets the value of the variable “ans” to “yes” if the value of “condition” is true and “no” otherwise. 

Kotlin Ternary Conditional Operator

3. Use ‘when’ as Kotlin Ternary Conditional Operator

“when” is an expression in Kotlin that is a good alternative to the ternary operator. The when keyword is used for creating conditional expressions similar to a switch statement in other programming languages. It allows you to check a value against multiple possible conditions and execute different code blocks based on the first matching condition.

Following is the syntax of the ‘when’ statement.


// Kotlin when statement
val result = when (condition) {
    value1 -> expression1
    value2 -> expression2
    value3 -> expression3
    // ...
    else -> expressionElse
}

Here “condition” is any conditional expression, “value1”, “value2” etc are the keys and the “expression1”, “expression2” etc are the corresponding values of the keys. The “else” is returned if none of the previous conditions are satisfied. 

Following is an example 


// Example of 'when'
fun main() {
    val condition = true // Change this condition to true or false
    val ans = when (condition) {
        true -> "yes"
        false -> "no"
    }
    println("The ans is: $ans")
}

Yields below output.

4. Use Elvis Operator

The operator “?:” is popularly known as the elvis operator in Kotlin. It provides an elegant way to provide default values to nullable variables or expressions. Although we can do the same with if-else, case statements, the elvis operator is a better choice since it is short and more convenient to use and it is used to handle potential null values more gracefully.

The Elvis operator works by returning the value on the left-hand side if it’s not null, and if it is null, it will return the value on the right-hand side. This can be especially useful for providing a default value or a fallback value when dealing with nullable variables.


// Example of elvis
val result = expression1 ?: expression2

Here, expression1 is evaluated first and if it is null then expression2 will be returned otherwise the value of expression1 is returned.

Following is an example.


// Main function 
fun main() {
    val value: String? = null
    val result = value ?: "Default Value"
    println("The ans is: $result") // Output will be "Default Value" because 'value' is null
    val nonDefault = "Now it contains value"
    val nonDefaultResult = nonDefault ?: "Default Value"
    println("The ans is: $nonDefaultResult") // Output will be "Now it contains value" because 'nonDefault' has a non-null value
}

Yields below output.

Kotlin Ternary Conditional Operator

In the above example, we first declared a variable named value. However, we kept the value of the variable to be null. Next, we used the elvis operator. Since the value of the variable “value” is null, the variable got the default value string “Default Value”. 

In the second case, we set the value of the variable “nonDefault”. As a result, it did not receive the default value from the elvis operator. 

5. Conclusion

In this article, we learned about Kotlin Ternary Conditional Operator. Kotlin by default does not have any direct support to the ternary operator. However, there are several techniques that perform and look similar to the ternary operator. The “if else” statement, “when” expression, and elvis operators are some of the techniques that we can use as a replacement for the ternary operator in Kotlin.