Stealing the idea to use quasiquotes from this answer, we first add the macro-paradise plugin:
// build.sbt
scalaVersion := "2.10.2"
resolvers += Resolver.sonatypeRepo("snapshots")
addCompilerPlugin("org.scala-lang.plugins" % "macro-paradise" % "2.0.0-SNAPSHOT"
cross CrossVersion.full)
Then the macro looks like this:
// src/main/scala/Foo.scala
import reflect.macros.Context
import language.experimental.macros
trait Foo[A]
class IntFoo() extends Foo[Int]
class AnyFoo() extends Foo[Any]
object Foo {
def apply[A]: Foo[A] = macro applyImpl[A]
def applyImpl[A](c: Context)(t: c.WeakTypeTag[A]): c.Expr[Foo[A]] = {
import c.universe._
val aTpe = t.tpe
val prefix = if (aTpe =:= typeOf[Int]) "Int" else "Any"
val clazz = newTypeName(s"${prefix}Foo")
c.Expr(q"new $clazz()")
}
}
And the test case:
// src/test/scala/Test.scala
object Test extends App {
val fooInt = Foo[Int]
val fooAny = Foo[Any]
println(fooInt)
println(fooAny)
}
Without the macro-paradise-plugin, you would need to construct the tree by hand, like New(clazz, ???)
, I couldn't get that to work so gave up, but it certainly would be possible, too.