views:

63

answers:

1

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 class 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?

+6  A: 

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"

Landei
Ok, thanks so much! It's perfect! But, another thing... How I can do this?: hello R true (note, without quotes)
isola009
`hello` is an identifier (that may refer to a type, a value or to nothing at all). `"hello"` is a string. There is no way to convert an arbitrary identifier to a string or any other value. The program text may create an referrent for an identifier (by defining it), but Scala isn't homoiconic as Lisps are so there's no way to get what (I think) you want.
Randall Schulz