How to define a ternary operator in Scala which preserves leading tokens?
Posted
by Alex R
on Stack Overflow
See other posts from Stack Overflow
or by Alex R
Published on 2010-04-24T19:54:57Z
Indexed on
2010/04/24
20:03 UTC
Read the original article
Hit count: 137
I'm writing a code generator which produces Scala output.
I need to emulate a ternary operator in such a way that the tokens leading up to '?' remain intact.
e.g. convert the expression c ? p : q
to c something
. The simple if(c) p else q
fails my criteria, as it requires putting if(
before c
.
My first attempt (still using c/p/q as above) is
c match { case(true) => p; case _ => q }
another option I found was:
class ternary(val g: Boolean => Any) { def |: (b:Boolean) = g(b) } implicit def autoTernary (g: Boolean => Any): ternary = new ternary(g)
which allows me to write:
c |: { b: Boolean => if(b) p else q }
I like the overall look of the second option, but is there a way to make it less verbose?
Thanks
© Stack Overflow or respective owner