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:
foo = 1;
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")
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).