2

I looked type macros for scala. But when i would like create object from example, i got error:

Example.scala:7: `=', `>:', or `<:' expected
type Test(url: String) = macro impl

Example.scala:12: illegal start of simple expression
val clazz = ClassDef(..., Template(..., generateCode()))

Code:

//Example.sbt
object Example {

  type Test(url: String) = macro impl

  def impl(c:Context)(url: c.Expr[String]):c.Tree = {
    import c.universe._
    val name = c.freshName(c.enclosingImpl.name).toTypeName
    val clazz = ClassDef(..., Template(..., generateCode()))
    c.introduceTopLevel(c.enclosingPackage.pid.toString, clazz)
    val classRef = Select(c.enclosingPackage.pid, name)
    Apply(classRef, List(Literal(Constant(c.eval(url)))))
  }
} 

Scala version: 2.10.2

From: type macros

lito
  • 989
  • 8
  • 21

1 Answers1

3

If only it were that easy! From the documentation you link to:

Type macros are a pre-release feature included in so-called macro paradise, an experimental branch in the official Scala repository. Follow the instructions at the "Macro Paradise" page to download and use our nightly builds.

And:

Please note that due to binary compatibility restrictions, macro paradise for 2.10.x doesn't include any features from macro paradise 2.11.x except for quasiquotes.

So you're going to have to move to the Macro Paradise branch for 2.11 if you want this to work.

Note also that the ... in the type macros documentation is intended to indicate elided code—you can't just copy and paste it.

Travis Brown
  • 138,631
  • 12
  • 375
  • 680
  • thanks. But is there another way to generate class definitions? – lito Jun 26 '13 at 18:16
  • In 2.10? Kind of. You can generate an anonymous class instance with arbitrarily-named members and it'll have an inferred structural type that includes those members. See [these](http://stackoverflow.com/q/13669974/334519) [questions](http://stackoverflow.com/q/14370842/334519) or [my blog post here](http://meta.plasm.us/posts/2013/06/19/macro-supported-dsls-for-schema-bindings/) for some examples. – Travis Brown Jun 26 '13 at 18:22
  • Thanks Travis for the replies. – lito Jun 26 '13 at 18:25