Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate a class with Scala Macro or reflection

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?

like image 280
Maurício Szabo Avatar asked Sep 16 '13 22:09

Maurício Szabo


1 Answers

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.

like image 128
Travis Brown Avatar answered Nov 06 '22 15:11

Travis Brown