Domanda

I never liked the new operator in Scala, particularly for DSLs. The workarounds for constructing objects without new are usually quite ugly. For instance, if you import scala.actors.Actor._, you have actor { ... }, but inside the body you are not having access to this: Actor, so there is all sorts of pseudo instance methods in that object, too, like receive, react, self, etc.

With Scala 2.10 macros, I wonder if there is a chance to get the following working?

object Button {
  def apply(body: ? ): Button = macro applyImpl(body)
  def applyImpl(c: Context)(body: c.Expr[ ? ]): c.Expr[Button] = ?
}
trait Button {
  def text: String
  def text_=(s: String): Unit
  def doSomething(): Unit
}

Button {
  text = "test"
  doSomething()
}

As an additional challenge, what happens if doSomething is protected?

È stato utile?

Soluzione

I don't think this will work, since

{
   text = "test"
   doSomething()
}

won't compile, as there is no text and no doSomething() method outside of the Button trait. Macros can currently only work on expressions that have already been typechecked.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top