Adding a trinary operator in scala

I know that one of the issues people have with the language is not having a trinary operator in the std.
Is there specific reason for not adding syntactic sugar like: {Boolean ? x | y }
If not I would be happy to add it if no one is against it.

You can implement something similar in a library by making the first operator ? create a “curried” type whose only method is the second half | of the operator.

Conversely, since ? is a valid (definable) operator, making a builtin trinary operator would making parsing more ambiguous.

Do people really care strongly about this? In general, or because they’re used to having the ?: operator in the C language family? I find the need mostly obviated by the fact if is an expression.

I think the reason is that cond ? x | y doesn’t save much typing over if (cond) x else y, but it adds another language construct to remember and maintain; so I believe most people are against adding it, because they see it as unnecessary.

7 Likes

I have the following in my util package object

@inline def ife[A](b: Boolean, vTrue: => A, vFalse: => A): A = if (b) vTrue else vFalse

Agreed with the above: languages with the trinary operator tend to have if as a statement rather than an expression, so it’s necessary. That’s not the case in Scala, and personally I think just spelling out the if is much more readable…

3 Likes

Okay thanks for the input guys, maybe its inside my own little bubble but I see people complaining if else adds clutter to the code ( which I agree with ) and as the trinary operator is not just a “c” thing thought it might be nice.
But thanks for clearing this up, and giving explanation on why not add it.

This is clearly one of those examples of code readability being heavily influenced by what the reader is used to.

5 Likes

Yep! In Scala, if/else is the same as the ternary ?:. It’s something that is weird for people used to C-style languages where if doesn’t yield a value, just side effects.

Having said that, sometimes I wish for things to help avoid having to type if/else. Mostly I’d like something like Option.condition[A](boolean)(=>A): Option[A]. Other than that, if/else has been fine.

In Scala 2.13 there are methods Option.when and Option.unless: https://scala-lang.org/files/archive/api/2.13.0-RC1/scala/Option$.html

5 Likes