Ternary operator

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.

4 Likes