Ternary operator


Could you given an example, using Kotlin’s if statement expressions, where this is true?


if so, why did you use ternary operator, if you could simply write if/else instead of using it? Every ternary operator could be replaced with if/else in java/c++/… ?


I don’t mean to be rude, but I am certain you are not understanding my previous statements. Please re-read them carefully. I will also try again to explain. :slight_smile:

In Java/c++/etc, if statements are weaker than Kotlin’s. In Kotlin, if statements can RETURN something. In Java/c++/etc, if statements can NOT return things.

So, in Java/c++/etc, you can NOT simply replace ternary operators with if statements and also maintain single-expression format you do with inline functions. For example, in Java you can say:
final String fooBar = condition ? "foo" : "bar";
This is nice since you can make fooBar final. i.e. encouraging immutability.
In Java, the equivalent code would be something like:

String fooBar = null
if (condition) {
    fooBar = "foo";
} else {
    fooBar = "bar";

This is obviously ugly, verbose, and we lost the ability to make fooBar final!
So you can NOT simply just re-write it as a trivial if statement.
To do the same thing you’d have to wrap the if condition in a method. For example,

final String fooBar = buildFooBar();
private String buildFooBar() {
    if (condition) {
        return "foo";
    } else {
        return "bar";

that’s a lot of code! And WAY uglier/verbose. This is way so many Java/C++/other language users DO use ternary operators; because it’s the cleanest way in those languages.

As you can see it’s a lot of verbosity to re-write the ternary statements into equivalent if statements.

Now, Enter Kotlin:
Kotlin recognizes that the options in Java are not great, and often encourage either really verbose code, or bad practices. (i.e. people will not use the final keyword since it’s verbose. you should use final everywhere)

The fundamental problem with Java if statements is that they do NOT return anything, i.e. they are not expressions in the pure sense.

First, Kotlin makes immutability easy with val vs var. This makes making final values trivial.
Second, Kotlin makes if statements function as expressions like every thing else. This means Kotlin if statements can RETURN something.

As such, that long ugly Java (basically same in C++) can be re-written as:
val fooBar = if (condition) { "foo" } else { "bar" }

Notice how the if statement is returning something?
THIS is part of what makes Kotlin if statements so powerful.
THIS is also the use-case that people are wanting to solve when they use ternary operators.
You can NOT trivially do this in Java/C++ without a lot of verbosity, as demonstrated above.

Because of the power of Kotlin’s if statements, ternary operators are completely unnecessary in Kotlin.

I hope this makes things more clear.


ok, i agree with you, but i better write ternary operator instead of if/else in simple cases, like this:

return (!response.isSuccessful()) ? "fail" : response.body().string()


I don’t see how that is better than

return if (response.isSuccessful()) response.body().string() else "fail"

I think the Kotlin code is easier to read because you can read it from left to right.


As mentioned by Jonathan and others, you aren’t saving yourself anything except a few characters.

? : vs if else

The only reason ? : is easier for you to read is because you’ve already learned the ? : operator.
I promise you 100%, if you take the two examples to someone learning programming, they will 99% choose the if else option.

Why do you want two ways to do the exact same thing? This only further and unnecessarily complicates the language.

To me this is similar to people wanting to use single letter variable names because they think making a slightly longer, but easier to read, variable name is harder to read.

Clarity of code almost always wins.


maybe it is about habit, but if i come across more simple form of if/else like ternary operator and, if i have examples of if/else and ternary operator to compare them with each other, i would use ternary operator, as it would look more simple.


I needed several years to get used to the conditional operator. And I still don’t like it today. I’m happy that some modern languages like Kotlin and Scala have abandoned this readability nightmare.


As others have said many times in this thread, the power that if statements have in Kotlin makes the ternary operator obsolete. Also, using code golfing, or number of characters as a proof that the ternary operator is better seems to be some broken logic. Sure, if you’re purposely trying to golf something, it might be useful. But in production code, you’re going to want to maximize readability.


it is very doubtful.


maybe obsolete, maybe not, but in the case of ternary operator it is both simple to write and simple to read, if i aint need to write if/else, i would avoid writing if/else. if it is useful, it would be used if it even looks obsolete;
or you mean planned obsolescence?


I mean that the ternary isn’t necessary anymore. In Kotlin, the only benefit a ternary would have over if/else as an expression is the number of characters, and as was said earlier, that’s no reason to add it to the language.


Whatever the merits of the ternary operator, the fact is that, if it were introduced now, it wouldn’t play too well with the safe call (?.) and Elvis (?:) operators.

For this reason and because it has nothing to do with nullability (which ? now suggests), the chances of it being added to Kotlin are remote IMO.


By the way, elvis operator itself is a bit alien to kotlin. It comes from groovy where it is a logical consequence of groovy truth concept. Kotlin does not have the same construct, so elvis operator looses its initial meaning. Well, it is just another operator now.


Yes, the ‘Elvis’ operator has its own page on Wikipedia where it mentions (and links to) the usage of this operator in Groovy and several other languages.

One thing that hadn’t dawned on me previously is that it originated as a special case of the ternary operator with the second operand missing and then evolved into a binary operator i.e. you can’t now separate the ? and the : symbols.

So, even if he can’t have the ‘unadulterated’ ternary operator, @edgeone may discover a new found enthusiasm for Elvis. :slight_smile:


I agree with you on all that you were saying, but a technical nitpick here. The reason you could not put final on this is not because of the if, but that you initially assign null (intellij should even warn you about the unnecessary assignment).

This is valid Java:

final String fooBar;
if (condition) {
    fooBar = "foo";
} else {
    fooBar = "bar";


The equivalent Kotlin code is also valid Kotlin (without if as expression).


Not only that, but ?: Is used as a null check for nullable variables as well.


I programmed in c# for 10 years and I love conditional operator. I dont suggest that it must be ?: ( it can be whatever we want, for instance => : ) but I think that giving developer a choice what to use is always a good thing.


No, it’s not. More than one (obvious) way to do it leads to diversity without real advantages. But it leads to higher coginitive load, higher learning costs and more bugs.