Even as an option this would be breaking, because I am 100% sure there are people out there (me included) who have functions named begin and end
And srsly âCoroutines are confusingâ is not an argument for the ternary operator. Yes they might be, but there is no better option. For the ternary operator there is an option and I would argue a better one.
I made a summary of the whole topic and the arguments (named once or over and over).
But before the discussion, its important to know what is possible:
(success) ? first() : second() //possible
(success) ?: second () // not possible as it checks if success is null
Next, I didnât want to chain facts between opinions, as it makes the opinions look like facts.
I couldnât however distinguish all the facts from opinions, so I could have made some facts opinions and vice versa. The opionions are cursive.
Next, I tried to be unopinionated, but Iâm against the ternary operator. This can be reflected below.
A lot of languages have it which:
- makes the conversion from those languages harder
- means that the construction should be unlearned by those programmers.
It looks less verbose
Its shorter
but its at most 6 chars shorter
being short is not a goal of kotlin
The choice should be left upon the programmers
but more concepts for the same thing is harder to learn.
cons:
for (at least) beginning programmers: it is hard to learn.
Its not a priority (at the moment) so the attention can be focussed on more important things
The questionmark in Kotlin is associated with null:
- the shorthand if/else ?: is not even possible.
- the code can be interpreted different: success? foo : bar can be interpreted as if(success == null) foo else bar
Itâs not needed as:
If is already an expression
you can create a comparable function yourself infix fun <T : Any> Boolean.t(value: T) : T? = if(this) value else null
(I however recommend you not to use this)
When something is not on the list, please respond. Otherwise, we just keep repeating ourselves.
Sorry to take so long to get back to you. You completely ignored my distinction between groups 2, 3, and 4 which all fall into your group about being âteachedâ a C like language. I didnât contradict the assertion that many are taught a C-like language and estimated the figure at 90%. But just because they learned Java or similar language does not mean that ternary operator is easier to read to them.
There is plenty of other evidence. As I have said the fact that ternary operator is used so infrequently in Java code even though it actually has a reason to exist in Java is one piece of evidence. Googling and seeing how many peope say donât use it because it is harder to read is also good evidence.
I, for one, emphatically throw my hat into the ring in favor of the standard C-style ternary operator. While Iâm not averse to shaving away questionably or unnecessary functionality that does not make sense in the new language (such as old for-style loops), this is just change for the sake of change. Itâs no less ugly than the traditional method, itâs bulkier making it harder to cleanly fit on a single line, but also lopsided in a way that doesnât lend well to splitting up over multiple lines (at least for that there are when statements). And itâs honestly rather confusing in an extremely subtle way that would, if anything, only trip up beginner programmers.
Someone who doesnât know what a ternary operator is will see âx = a ? b : câ and think âI donât know what this is, I should look it up.â They see x = if( a) b else c they might say the same thing or they might say âWhat is this, some sort of predicate? Is x a value or a command path? I know what an if-else block is, is this a standard if else block? What does assigning that even do? Can I do that with other control structures?â
The fact that even IntelliJ IDEA has problems formatting the if-else syntax mid-editing because it thinks its a malformed if-else block until itâs completely finished should tell you that youâre probably going about this the wrong way.
Frankly, if you donât have the balls to remove the ternary operator entirely, donât give it some confusing coat of paint to make it âmore obvious.â
I, for one, emphatically throw my hat into the ring AGAINST the standard C-style ternary operator
And this is definitely unnecessary functionality with if-else expressions.
The phrase you are looking for is âeasier to readâ.
ternary operator is the most lopsided operator there is because it is a postfix on the condition. Imagine reading from right to left, x = a, ok a gets assigned to x, now ?, WTF? x = a ? b, WTF?, x = a ? b :, Huh?. Compare that to x = if, OK at this point I know x is getting assigned the result of a conditional.
The phrase you are looking for there is âhard to readâ or âunobviousâ. And they will likely have to repeatedly look it up.
They see that and they already know what an if-else is. Only difference is that it has a value instead of continuing the artificial Java and C limitation that if has no value. Lots of other languages already have if-expressions and this is easy for them to read. I think a non-programmer could figure out what x = if(a) b else c means.
Certainly no one is talking about removing conditional expressions. Ternary operator exists ONLY because in C if was a statement not an expression. With that limitation gone ternary operator has no reason to exist.
Itâs interesting to compare Swiftâs reasoning for having the ternary operator instead of if else as expression.
In this message Chris Lattner lists the cons of if then else expression:
It is substantially more verbose than ?:, so much so that it obscures the logic that was trying to be captured.
It looks like if statement, however it is semantically different
It forces indenting a lot when branches have long expressions
Then he lists the pros of the ternary operator:
It is extremely concise, and covers a very common pattern.
It is pervasively standardized in a very wide range of languages.
Itâs weird syntax reduces the odds that people would flow it out and use very large expressions in it.
It chains well for multiple conditions because of its associativity.
However he also admits the cons of the latter:
?: is ugly and magic, and is an additional thing people have to learn if coming to swift without encountering a C family language.
it is unfortunate that it uses â?â in particular, since theyâd prefer that to be associated with optionals.
And here he even said that heâd love to see the weird ?: ternary operator get nuked and replaced with an if/else expression of some sort.
The links were taken from Commonly Rejected Changes page, so I believe these messages represent the Swift teamâs point of view.
In the end he says âwe only change things when there are strong reasonsâ and I think this applies to the situation with the ternary operator in Kotlin too
I hate that everything for ternary is on place and you can in fact create one:
operator fun <T> Boolean.plus(firstValue: T): FirstValue<T> = FirstValue(this, firstValue)
operator fun <T> FirstValue<T>.minus(secondValue: T): T = if (bool) firstValue else secondValue
data class FirstValue<out T>(val bool: Boolean, val firstValue: T)
fun test(){
val biggerTitle = (3 < 2) + "positive" - "negative"
}
but you need to use some other operators like plus minus or other names and therefore its out of standard and much harder to understand!
I dont really understand why to include e.g. array def via but not ternary.
fun <T> Boolean.thenElse(onTrue: T, onFalse: T): T = if (this) onTrue else onFalse**
fun <T> Boolean.thenElse(onTrue: () -> T, onFalse: () -> T): T = if (this) onTrue() else onFalse()
val isConditionSatisfied: Boolean = ...
val result = isConditionSatisfied.thenElse("something1", "something2")
You just canât write it with if/else to be nicely formatted. This is just one example I took from my head but I encounter such patterns at least few times a day.
IMHO if/else should be if/else, not ternary. It is a plus that you can assign them as expressions but only a plus. It shouldnât forbid proper ternary operators. Maybe itâs me but It just doesnât look nice and much harder to read. Also I always catch myself on trying to avoid if/else (ternary) at all because of that.
When is more verbose and you should understand that takeIf/let/?: looks ridiculous. Understand, Iâm not looking for workarounds as I can come up with lots of them myself.
I donât understand why a lot of people support Elvis operator and are against ternary one. They essentially have the same story and very similar in implementation:
Elvis transforms if (a != null) a else b
into a ?: b
And ternary transforms if (condition) a else b
into condition ? a : b
As explained above (like a million times) the ? in Kotlin is an character associated with nullability. IMO this is the main reason why the ternary operator would not really fit into Kotlin. Also as explained above, the fact that if else are not statements but expressions means that the ternary operator is not needed. Yes it would be a bit shorter and some people argue even more readable, but it would not add anything new to Kotlin.
The reason why languages like Java or C++ have the ternary operator is because they canât do stuff like
int foo = if(someCondition) 1 else 2;
They would need to write this:
int foo;
if(someCondition)
foo = 1;
else
foo = 2;
The fact that Kotlin treats if else as an expression and not a statement means that Kotlin basically already has a ternary operator (just with a different syntax).
I personally would support the ternary operator if not for the ?. I think it should not be used outside of the context of nullability.
As to the fact that if else is to verbose. I personally donât like either syntax inside of a more complex expression as both tend to become to verbose in more than just the most basic examples. In those cases I just usually just declare a temp val. This is the most readable way to solve this problem IMO. And when you declare a temp val it does not matter whether you use if else or the ternary operator:
String value = (storeType == StoreType.Database)
? getDatabase().getSettingsDao().getString("my value")
: getSettingsHelper().getSharedPreferences().getString("my value")
val value = if(storeType == StoreType.Database) getDatabase().getSettignsDao().getString("myValue")
else getSettingsHelper().getSharedPReferences().getString("myValue")
The only problem with this so far is the fact that the code style rules donât really support proper alignment and indentation. But once you are used to this, not indenting the else is not even that bad (even though I would prefer it to be indented).
It is a good sign for Kotlin that this (superfluous) discussion is one of the most popular here. It seems like Kotlin doesnât have any real problems
Is there some design document with a reasoning why the conditional operator (ternary operator is a bad name) is not included in Kotlin and never will be? This document could be linked here so that this discussion could end.
Iâm not aware of any document regarding this. I guess there was an internal discussion at JetBrains and they decided against it. And judging from the discussion here the community is split 50/50 ( I want to say 60/40 against it, but I am biased as well).
As for the name ternary vs conditinal. One ternary describes what it is (an operator with 3 arguments) and conditional describes the function (a condition) so I guess both fit.
Here (russian) @abreslav claimed that it was not a problem to add ? to the language as part of ternary operator, but the problem was to add :, because this symbol could be useful in other new syntax (collection literals, slices, etc)
Well, thatâs an interesting new slant on the matter!
Iâd always thought that the sticking point would be ? rather than : .
It certainly is for me because of its association with nullability.
As regards : I suppose they could use = instead for map literals and for slices they could use the range operator .. (and its associated functions until and step) though it would be a bit verbose compared to what other languages have.
18 year Java veteran here. I remember missing the ternary conditional operator when I dabbled in Scala, and Iâm feeling some of the same phantom limb twinges with Kotlin.
This is a widely-used construct in other C-like languages, and for programmers coming from that background, ? strongly connotes a general conditional expression. In consideration of Kotlinâs famously null-explicit type system, it may be purer semantically to relearn it in the narrower scope of âconditions involving nullâ, but that means getting used to some conditional expressions having a different form than others.
J x != null ? x : other
K x ?: other // love it
J x != null ? x.foo : other
K x?.foo ?: other // still loving it
J x != null ? f(x) : other
K x?.let { f(x) } ?: other // eh, itâs better than Optional.flatMap
J test ? x : other
K if (test) x else other // this is readable, but less familiar
I suspect that the number of times I actually need to use the last form is going to go way down, but it will take a while to get used to.
Iâve seen too many defects introduced by the ternary operator in Java so we actually started preventing it on a new project at my last company.
Weâre not so strict at my current company. Unfortunately many developers that like the ternary operator also like nesting a ternary inside another ternary which makes the code non-obvious, easy to misinterpret, and error prone. It got so bad that we added a rule that theyâre not allowed to be nested and the ternary operator can only be used when it fits on a single line.
I really like that Kotlin doesnât have the ternary operator and the if-expression is much more clear. I use this as a selling point when promoting Kotlin.
I think the argument that ? is associated with null only is wrong. If one look from natural languages perspective everything fits into places.
We use ? in questions and its exactly ternaryâs meaning. Ask and do something depending on the answer.
And we use ? to mark something questionable, about what we donât sure. Like this: