DEV Community

Angelo Moroni
Angelo Moroni

Posted on

Ternary Operator, I miss you

Kotlin is a wonderful language but I remember I was really sad when I saw that it doesn't have the ternary operator. I was a Java developer and I have user this operator a lot of times because I think it's fast to write and easy to read.

Wait, wait, yes: I know that if expression returns a value, but I think writing an if is superfluous when the body has only one instruction.

For example:

I'd rather write this code

val foo = booleanValue ? something : anythingElse
Enter fullscreen mode Exit fullscreen mode

than this

val foo = if (booleanValue) something else anythingElse
Enter fullscreen mode Exit fullscreen mode

Also, since the body may present a complicated expression, using the ternary operator I could write fewer lines of code.

Yes, you're right, I'm lazy; but If I wasn't so lazy, I'd be a farmer instead of a developer.

And yes you're right when the code is too much concise, it is less readable and I also believe that balance between readability and brevity is a good thing, but I don't think that ternary operator is the problem.

In fact, Kotlin advocates suggest us to avoid a list of if because it can lead to many bugs and so why shouldn't the ternary operator be kept?

What do you think about it? Do you agree with me?

Top comments (1)

Collapse
 
mirceanis profile image
Mircea Nistor

I guess writing code with fewer characters is not a goal of kotlin.
I agree that it's not fun to lose the ternary.
The actual operators I miss are bitwise operators on Integer types
c/c++/Java/c#/..: (foo & 0xFF ) << 8
kotlin: (foo and 0xFF) shl 8