Scala 实例化密封类的隐式转换

Scala 实例化密封类的隐式转换,scala,implicit,case-class,Scala,Implicit,Case Class,我有这份遗产 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 /* ... */

我有这份遗产

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
/* ... */

但是,我想这样做:

"hello" MyR true // R(MyString("hello"), MyValue(true))
我该怎么做?

这个怎么样:

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 /p>>p>这个如何:

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 /p>”。也许可以改变你问题的标题?据我所知,这门课是密封的并不重要。也许可以更改你问题的标题?好的,非常感谢!太完美了!但是,另一件事。。。我怎么能做到这一点呢?:hello R true note,不带引号hello是一个标识符,它可能引用类型、值或什么都不引用。你好是一根弦。无法将任意标识符转换为字符串或任何其他值。程序文本可以通过定义标识符来创建标识符的引用,但是Scala并不像Lisps那样具有同构性,因此无法获得我认为您需要的内容。好的,非常感谢!太完美了!但是,另一件事。。。我怎么能做到这一点呢?:hello R true note,不带引号hello是一个标识符,它可能引用类型、值或什么都不引用。你好是一根弦。无法将任意标识符转换为字符串或任何其他值。程序文本可以通过定义标识符来创建标识符的引用,但是Scala并不像Lisp那样具有同音性,所以无法获得我认为您想要的东西。