Creating a class using Scala Macro or reflection

In my scala code, I want to be able to instantiate a new class. For example, suppose I have the code below:

class Foo { def foo=10 } trait Bar { val bar=20 } 

Ideally, I want to do something like:

 def newInstance[A <: Foo] = { new A with Bar } newInstance[Foo] 

But of course this will not work. I tried using reflection to create an instance of the class, but it seems that I can only create a new class (and not mix with the attribute). I think it would be possible to do this work with macros, but I'm not sure where to start.

What I'm trying to do is similar to the following Ruby code:

 class SomeClass def create self.class.new end end class Other < SomeClass end Other.new.create # <- this returns a new Other instance 

Is it possible?

+7
macros reflection scala scala-macros
source share
1 answer

With macro:

 import scala.language.experimental.macros import scala.reflect.macros.Context object MacroExample { def newInstance[A <: Foo]: A with Bar = macro newInstance_impl[A] def newInstance_impl[A <: Foo](c: Context)(implicit A: c.WeakTypeTag[A]) = { import c.universe._ c.Expr[A with Bar](q"new $A with Bar") } } 

This will work as expected, and will work at compile time if you try to instantiate a class that has no constructor with no arguments.

I used quasiquotes here for clarity, but you could build the tree manually with a little work. However, in fact, there is no good reason for quasivotes to be available as a plug-in for Scala 2.10.

+11
source share

All Articles