Every developer, one day or another, came across a situation where a variable should get a value or another based on a simple condition. In most programming languages you are able to write something like
variable = (condition) ? <then> : <else>, in which if
condition is true then
variable takes the value of
<then>, else it takes the value of
<else>. Pretty straightforward.
In Kotlin, you can’t.
Let’s take a look at the following function (pseudocode):
The ternary operator here allows us to write this function body in just a single line. So why this doesn’t work in Kotlin? It doesn’t work because of a simple difference between Kotlin and most other languages:
if statements are expressions.
What does that mean? It means
if resolves to a value, so you can directly use it when assigning a variable.
Let’s see this in action. Here is the above function written in Kotlin and in the most verbose way possible:
Ew. This hurts to read. Let’s try to make it better. First of all, we’ll take advantage of what we said earlier. We can use
if directly in the variable assignment (which also let us use
val instead of
var because we’re not reassigning it):
This is like a verbose version of the ternary operator we’re used to see.
value will be either
"Text is long" or
"Text is short" based on the length of
text directly in the assignment. This is something you can’t do in most other languages.
That’s cool, but let’s make it even shorter by inlining the
if, removing the unnecessary curly brackets and directly returning the value:
There it is. This is the same as the first code block I’ve written.
Ok, that’s fun and all. But what if you’re that accustomed to the classic ternary operator that you can’t stand to actually read
There’s a solution for that. We can write our own function to kind of emulate that. The function is this:
Let’s analyze it. It basically checks the condition and if it’s true returns the value we pass to the function, else it returns
How is that useful to us? We use it to check the condition, and then use the Kotlin Elvis operator to specify the
The same final function from before written using our shiny new method will be:
That is pretty neat to read! Notice there is no dot or parentheses when we call
.then(), and that is thanks to the
infix modifier we specified. This does exactly the same thing as before, but now almost looks like our standard ternary operator.