Here is the Kotlin interpretation of the code above if the syntax of the second line would be available:
- If
success()
(which returnsBoolean
) returnstrue
, then use"foo"
, else use"bar"
. - If
success()
(which returns a nullable type) does not returnnull
, then use"foo"
, else use"bar"
. - If
success()
(which (likely) returnsString?
) does not returnnull
, then use its result, else use"bar"
.
And here is what you think the second line should mean:
- If
success()
(which returnsBoolean
) returnstrue
, then use"foo"
, else use"bar"
.
Do you see that with your interpretation, very similar syntax: ? <some value> : <some value>
and ?: <some value>
, has different semantics: control flow and null
handling respectively? It is precisely this inconsistency that the language designers (and a lot of developers) do not want in the language.
Kotlin is not a copy of another language because that would be useless. The Kotlin designers have looked at lots of constructs from many languages, experimented with them, and finally chose the ones that resulted in what Kotlin is now. Is it perfect? No. Will it have what all developers are familiar with? No. Is it an awesome language with awesome (future) possibilities? Yes. Does it require you to study and change your mindset? Yes (like all languages do).
I don’t know which language you use the most, but I have been using Java for over 20 years now. Just the facts that I can write the same functionality in about half the code, and that I have to worry about possible NullPointerException
s a whole lot less, makes Kotlin worthwhile for me. Even if it does not have one particular feature that I like very much.
You have to consider the same thing: Is a missing ternary operator more important than all the things I do get from Kotlin? If you do decide to stick with Kotlin because you value the other things you get from it more, please accept that the ternary operator (in the form that you propose) is very likely not going to be added. There is an issue: Support ternary conditional operator ‘foo ? a : b’ , for it, you can vote there, and hope for the best.