Generic Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Overview

Briefly speaking, there is no ternary operator in Kotlin. However, using if and when statements help 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.

Generic bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

2
Leave a Reply

avatar
0 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
0 Comment authors
Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
nwillc
Guest
nwillc

Don’t you step on my blue suede operator! Don’t forget the Elvis!

val l = b?.length ?: -1

Loredana Crusoveanu
Guest

Hi Will,

Thanks for the feedback. We’ll update the article.

Cheers.