Ternary operator

I think your idea (bodyOrNull) is only useful in some special cases. The purpose of ternary operator is for more general cases. The main advantage of using ternary operator is making code concise when the logic is short. This kind of logic happens very often in real life. Let’s compare these 2 versions:

val v = if (b) x else y // 23 chars
val v = b ? x : y // 17 chars (saved 6 chars = 26%)

In the case of @edgeone:

result = if (response.isSuccessful()) response.body().string() else "fail" //74 chars
result = response.isSuccessful() ? response.body().string() : "fail" //68 chars (saved 6 chars = 8%)

IMO, saving 26% of time for typing in first case is really a good deal, plus the code in 2nd line is very clean and easier to read. For the later, we can only save 8% of time. If the expression is longer, it would be better to use if/else and separate into multiple lines to improve code readability.

I am really wonder why Kotlin doesn’t support this feature. The goal of Kotlin is to be better than Java, but in this case, it is not.

7 Likes