Kotlin Ternary Conditional Operator Examples

1. Overview


In this article, We will learn Ternary Operator in Kotlin and this is part of conditional statements. But, confirming now there is no ternary conditional operator in kotlin language. Let us see how we can simulate or mimic the same using other condition statements available. By the end of this article, you will understand why no ternary conditional operator introduced in kotlin.

If you are new to kotlin language, see the simple hello world-first program in kotlin.

This can be achieved using if-else and when statements.

Kotlin Ternary Conditional Operator




2. Using If-Else 


Unlike other programming languages, if-else is considered as an expression. The result returned by this if-else can be stored in a variable. So now, this is giving a hint to us how we can mimic ternary with if-else.

Let us take a look at the below example

Example:

[val result = if (value) "yes" else "no";]

In the above expression, if the value is set to true, our result variable will be set to yes. Otherwise, it is set to no.

Here result type is String but we have declared as val. So keyword val will cast based on the returned value type.

Another example:

[val result: Boolean = if (a == b) true else false;]

This checks the condition a==b which means if values of a and b are equal then returns a boolean true otherwise false.

Here boolean value will be cast by val.

3. Using When


Similar to the above, when statement is called expression and it returns a value. So, when also can be used as an alternative to the if-else for the ternary condition.

Example:

Let us see the example.

[val result = when(value) {
true -> "yes"
false -> "no"
}]

If when the condition is true it returns "yes" if it is false returns "no". Here when is returning a String type.

Another Example:

[val result = when(a == b)) {
true -> true
false -> false
}]


If a==b condition is true then it returns boolean true. Otherwise returns false.

4. Conclusion


Note: There is a temptation mechanism to create a DSL that mimics a ternary operator. But, Kotlin's language restrictions are too tight to allow for a 100% reproduction of the traditional ternary syntax.
As such, let's avoid this temptation and simply use one of the earlier mentioned solutions.

In this article, we have already mentioned that Kotlin does not support for the ternary operator because this can be achieved by using if-else and when expressions.

Kotlin Ternary Conditional Operator

0 Comments