λ Tony's Blog λ
Does Scala have Java's ternary operator?Posted on October 13, 2008
I hear this question a lot. Yes it does. Instead of
c ? p : q, it is written
if(c) p else q.
This may not be preferable. Perhaps you’d like to write it using the same syntax as Java. Sadly, you can’t. This is because
: is not a valid identifier. Fear not,
| is! Would you settle for this?
Then you’ll need the following code. Notice the call-by-name (
=>) annotations on the arguments. This evaluation strategy is required to correctly rewrite Java’s ternary operator. This cannot be done in Java itself.
Here is an example using the new operator that we just defined:
Have fun ;)