我正在编写一个生成Scala输出的代码生成器.
我需要模仿一个三元运算符,使得令牌导致'?' 保持不变.
例如,将表达式转换c ? p : q为c something.简单if(c) p else q不符合我的标准,因为它需要放在if(前面c.
我的第一次尝试(仍然使用上面的c/p/q)是
c match { case(true) => p; case _ => q }
我找到的另一个选择是:
class ternary(val g: Boolean => Any) { def |: (b:Boolean) = g(b) }
implicit def autoTernary (g: Boolean => Any): ternary = new ternary(g)
这让我写:
c |: { b: Boolean => if(b) p else q }
我喜欢第二个选项的整体外观,但有没有办法让它更简洁?
谢谢