从这个答案中窃取使用准引号的想法,我们首先添加宏天堂插件:
// build.sbt
scalaVersion := "2.10.2"
resolvers += Resolver.sonatypeRepo("snapshots")
addCompilerPlugin("org.scala-lang.plugins" % "macro-paradise" % "2.0.0-SNAPSHOT"
cross CrossVersion.full)
然后宏看起来像这样:
// 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()")
}
}
和测试用例:
// src/test/scala/Test.scala
object Test extends App {
val fooInt = Foo[Int]
val fooAny = Foo[Any]
println(fooInt)
println(fooAny)
}
如果没有macro-paradise-plugin,您将需要手动构建树,例如New(clazz, ???)
,我无法让它工作,所以放弃了,但它当然也是可能的。