Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

Kotlin Ternary Conditional Operator

$
0
0

1. Overview

Briefly speaking, there is no ternary operator in Kotlin. However, using if and when statements helps to fill this gap.

In this tutorial, we'll look into a few different ways to mimic the ternary operator.

2. if and when Expressions

Unlike other languages, if and when statements in Kotlin are expressions. The result of such an expression can be assigned to a variable.

Using this fact, both if and when can be substituted for the ternary operator in their own way.

2.1. Using if-else

Let's take a look at using the if expression to mimic the ternary operator:

val result = if (a) "yes" else "no"

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

It's worth noting that the result type depends upon the expression on the right side. In general, the type is Any. For example, if the right side has a Boolean type, the result will be Boolean as well:

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

2.2. Using when

We can also use a when expression to create a pseudo-ternary operator:

val result = when(a) {
  true -> "yes"
  false -> "no"
}

The code is simple, straightforward, and easy to read. If a is true, assign result to be yes. Otherwise, assign it to no.

2.3. DSL

There's certainly a temptation 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.

3. Conclusion

Although Kotlin does not have a ternary operator, there are some alternatives we can use – if and when. They are not a syntactic sugar, but complete expressions, as we have seen previously.

As always, the code is available over on GitHub.


Viewing all articles
Browse latest Browse all 4535

Trending Articles