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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks. But is there another way to generate class definitions?
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 questions or my blog post here for some examples.
Thanks Travis for the replies.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.