Ternary operator

I know what I said :slight_smile:

And yet there are modern languages with both ternary and if expressions
Maybe there was no problem at all? And ternary was added for convenience

Apparently not since you denied saying it.

Are there, really? The primary C-based languages Java, Javascript, C#, Swift, C++, and C for example do not have if EXPRESSIONS, they have if STATEMENTS. To be clear an if expression allows you to say:

result = if(a < b) c else d

That is not allowed in any of the above mentioned languages. Kotlin does allow this and thus there is no need for the ternary operator.

Ruby is the only language I know of that has both and I dismiss any idea that we should look at Ruby for best programming practices.

For reference see Wikipedia: Ternary conditional operator - Wikipedia

2 Likes
  1. how about a bit another syntax
    condition ?? onTrue : onElse
    condition ?? onTrue ?: onFalse
    condition => onTrue ? onFalse
  2. temporal solution:
    operator fun Boolean.rem(t: T) = if (this) t else null
    val t1 = true % 1 ?: 2
    val t2 = false % 1 ?: 2

This removes the only advantage the ternary operator has, the old, familiar syntax.

1 Like

If is not a goal of kotlin save characters, then why do not use “function” instead of “fun” for define a function? For me, the ternary operator provides a short and concise way to declare a if else, because as say @nguyen-sde it is only a feature that is optional to use, if you consider that the if else sentence is more clear in your case, then use it but if you want to use the ternary operator I think that it should be allowed.
I do not understand why limit the language.
An example of why I prefer ternary operator over if else.

val result = if (expressionTooLong....................................................)
    resultA
else
    resultB

With ternary operator you could do:

val result = if (expressionTooLong....................................................)
    ? resultA
    : resultB

That is more clear at least for me.

5 Likes

Check out this topic: Please close the mega topics (ternary and companion objects)

This recent post is a post in response to the 8th post in this thread and is a really good example of how a mega thread isn’t able to end naturally:

The topics aren’t ending naturally
These topics are interesting and people will have an opinion on them. This is great until the topic becomes a place to petition for/against a position. Even though everything has been said, another user will come in support/against the feature of discussion without communicating anything new.


The original link is far enough up in the thread history that there’s a good chance people won’t see it and resume commenting on this thread.

Reposting hoping this link remains at the bottom :slight_smile:

2 Likes

Thank you, we have decided to close this topic. You can read the quick summary here.