开发者

Implicit conversion to instantiate a sealed class

I have this inheritance

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 clas开发者_如何学JAVAs MyU(m1:MyValue, m2:MyValue) extends MyValue
/* ... */

and

implicit def string2myString(s:String) = MyString(s)
implicit def boolean2myBoolean(b:Boolean) = MyBoolean(b)

But, I want to do this:

"hello" MyR true // R(MyString("hello"), MyValue(true))

How I can do it?


How about this:

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))

[Edit] I think regarding your second question Randall is right. If you just want the "optical effect" of a clean DSL, you might consider to use Symbols instead of Strings, e.g. 'hello instead of "hello"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜