Splicing together symbols with Scala macros

血红的双手。 提交于 2019-12-06 12:10:20
0__

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.

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