【问题标题】:Partial application of Scala macrosScala 宏的部分应用
【发布时间】:2017-07-01 10:05:20
【问题描述】:

说明问题的例子:

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]
*/

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

【问题讨论】:

    标签: scala macros scala-macros type-parameter


    【解决方案1】:

    输入 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(())
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      相关资源
      最近更新 更多