Instantiate a class with Scala Macro or reflection

两盒软妹~` 提交于 2019-12-21 12:29:42

问题


On my scala code, I want to be able to instantiate a new class. For instance, supose I have the code below:

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

Ideally, I want to be able to do something like:

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

But, of course this doesn't work. I tried to use reflection to instantiate a class, but it seems that I'm only able to instantiate a new class (and not mix-in with a trait). I think it would be possible to make this work using Macros, but I'm not sure even where to start.

What I'm trying to do is like 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?


回答1:


With a 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 fail at compile time if you try to instantiate a class that doesn't have a no-argument constructor.

I've used quasiquotes here for the sake of clarity, but you could build the tree manually with a little more work. There's not really any good reason to, though, now that quasiquotes are available as a plugin for Scala 2.10.



来源:https://stackoverflow.com/questions/18838533/instantiate-a-class-with-scala-macro-or-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!