1. Overview

Briefly speaking, there is no ternary operator in Kotlin. However, using if and when expressions 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 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 a 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 the result to be yes. Otherwise, assign it to no.

2.3. Elvis Operator

Sometimes, we use if expressions to extract some value when it's not null or return a default one when it's null:

val a: String? = null
val result = if (a != null) a else "Default"

It's also possible to do the same with when expressions:

val result = when(a) {
    null -> "Default"
    else -> a
}

Since this is such a common pattern, Kotlin has a special operator for it:

val result = a ?: "Default"

The ?: is known as the Elvis operator. It returns the operand if it's not null. Otherwise, it'll return the default value specified to the right of the ?: operator.

2.4. 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 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
nwillc
nwillc
8 months ago

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

val l = b?.length ?: -1

Loredana Crusoveanu
8 months ago
Reply to  nwillc

Hi Will,

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

Cheers.

Comments are closed on this article!