Scala宏的部分应用

时间:2017-07-01 10:05:21

标签: scala macros scala-macros type-parameter

说明问题的示例:

import scala.language.experimental.macros
import scala.reflect.macros.blackbox

object Test {
  def foo1[A, B]: Unit = macro impl[A, B]
  def foo2[A]: Unit = macro impl[A, Option[Int]]

  def impl[A: c.WeakTypeTag, B: c.WeakTypeTag](c: blackbox.Context): c.Expr[Unit] = {
    import c.universe._
    c.echo(c.enclosingPosition, s"A=${weakTypeOf[A]}, B=${weakTypeOf[B]}")
    reify(())
  }
}

/*
scala> Test.foo1[Int, Option[Int]]
<console>:12: A=Int, B=Option[Int]
       Test.foo1[Int, Option[Int]]
                ^
scala> Test.foo2[Int]
<console>:12: A=Int, B=Option[A] // <--- Expected: A=Int, B=Option[Int]
       Test.foo2[Int]
*/

为什么我们丢失了foo2中的具体类型?它看起来与foo1非常相似。

PS:我找到了一个可能不是最好的解决方案:

import scala.language.experimental.macros
import scala.reflect.macros.blackbox
import scala.reflect.runtime.universe.TypeTag

object Test {
  def foo1[A, B](implicit bTag: TypeTag[B]): Unit = macro impl[A, B]
  def foo2[A](implicit bTag: TypeTag[Option[Int]]): Unit = macro impl[A, Option[Int]]

  def impl[A: c.WeakTypeTag, B](c: blackbox.Context)(bTag: c.Expr[TypeTag[B]]): c.Expr[Unit] = {
    import c.universe._
    c.echo(c.enclosingPosition, s"A=${weakTypeOf[A]}, B=${bTag.actualType.typeArgs.head}")
    reify(())
  }
}

/*
scala> Test.foo1[Int, Option[Int]]
<console>:12: A=Int, B=Option[Int]
       Test.foo1[Int, Option[Int]]
                ^

scala> Test.foo2[Int]
<console>:12: A=Int, B=Option[Int]
       Test.foo2[Int]
*/

但问题的答案对我来说仍然很有趣。

1 个答案:

答案 0 :(得分:0)

输入Lambda

def foo2[A]: Unit = macro impl[A, {type A = Option[Int]}]

def impl[A: c.WeakTypeTag, B: c.WeakTypeTag](c: blackbox.Context): c.Expr[Unit] = {
  import c.universe._
  //Option[Int]
  println(c.weakTypeOf[B].members.find(_.isType).get.typeSignature)
  reify(())
}