In Java
bool boolean = true;
String s = boolean ? “true” : “false”;
I want the same in Kotlin
val boolean = true
val s = if(boolean) "true" else "false"
See also:
Yes it is, but it didn’t stop Java.) I’m killing a lot of time writing simple instructions.
I doubt it will be ever added, as it duplicates the existing and recommended syntax.
I agree with you, this Kotlin syntax is cumbersome. Kotlin syntax is generally nicer than Java, except for this conditional syntax, which is a shame.
There’s already been a centi thread on this:
I see little reason for this to change at any time
You can’t compare this directly with Java. Java’s if…else…
construct is a statement, not an expression, and so it needs a special syntax for a conditional expression (just like C before it).
However, Kotlin’s if…else…
is an expression. You don’t need anything else — it’s already right there in the language! Why clutter up the language with multiple bits of syntax doing exactly the same thing??
(And is writing ‘if
’ instead of ‘?
’, and ‘:
’ instead of ‘else
’, really so onerous? If the extra 4 characters is ‘killing a lot of time’, then maybe you could get some typing lessons or something? :-)
Well, type faster, my fingers are not rubber. You can also write “;” and “begin … end” for beauty. I don’t mind if Kotlin replaces mine ?: on if else. Although it’s strange not to keep up with Swift.
I wonder if you could combine infix functions?
infix fun <T> Boolean.`?`(options: Pair<T, T>): T = if (this) options.first else options.second
infix fun <T> T.`:`(other: T): Pair<T, T> = this to other
boolean `?` "true" `:` "false"
(I’m using the backticks because I’m pretty sure you’d have to escape the question mark and colon characters)
Now that I write it out, I can see another reason for not adding ternary expressions… since the question mark is already used for all sorts of null checks, and the question mark + colon is used for the Elvis operator, it might make the compiler very complicated if it also has to interpret question marks and colons as a ternary expression.
This works, but it doesn’t really replicate the functionality of if
, because it always evaluates both sides. For lazy bahavior, you would need something like
infix fun <T> Boolean.`?`(options: Pair<() -> T, () -> T>): T =
if (this) options.first() else options.second()
But then you would have to write
boolean `?` {"true"} `:` {"false"}