我有这种继承
sealed abstract class MyValue
case class MyString(s:String) extends MyValue
case class MyBoolean(b:Boolean) extends MyValue
case class MyR(m1:MyValue, m2:MyValue) extends MyValue
case class MyU(m1:MyValue, m2:MyValue) extends MyValue
/* ... */
和
implicit def string2myString(s:String) = MyString(s)
implicit def boolean2myBoolean(b:Boolean) = MyBoolean(b)
但是,我想这样做:
"hello" MyR true // R(MyString("hello"), MyValue(true))
我怎么做?
答案 0 :(得分:7)
这个怎么样:
class MyRBuilder(mv1: MyValue) {
def this(s:String) = this(MyString(s))
def this(b:Boolean) = this(MyBoolean(b))
def R(mv2:MyValue) = MyR(mv1, mv2)
}
implicit def stringToMyRBuilder(s:String) = new MyRBuilder(s)
implicit def boolToMyRBuilder(b:Boolean) = new MyRBuilder(b)
"hello" MyR true
//res2: MyR = MyR(MyString(hello),MyBoolean(true))
[编辑] 我认为关于你的第二个问题兰德尔是对的。如果您只想要干净DSL的“光学效果”,您可以考虑使用符号而不是字符串,例如'hello
代替"hello"