【问题标题】:Postpone implicit resolution until macro expansion将隐式解析推迟到宏扩展
【发布时间】:2021-03-24 02:52:27
【问题描述】:

考虑微不足道的宏:

def test[A](a: A): Unit = macro testImpl[A]

def testImpl[A: c.WeakTypeTag](c: blackbox.Context)(a: c.Expr[A]): c.Expr[Unit] = {
  import c.universe._
  println("Test running")
  c.Expr[Unit](q"")
}

及其调用

def foo(a: String)(implicit b: Int): Unit = ???

test(foo("123"))

它给出了一个错误

[error] Main.scala:19:18: could not find implicit value for parameter b: Int
[error]     test(foo("123"))

是否可以将隐式解析推迟到宏扩展时间或在这种情况下需要编写宏注释?

【问题讨论】:

    标签: scala metaprogramming implicit scala-macros


    【解决方案1】:

    与注解无类型注解的宏注解相反,def 宏的参数总是在宏展开之前进行类型检查。并且类型检查包括隐式解析。

    你也可以尝试做一个def宏的参数String

    test("""foo("123")""")
    

    (在test的定义中使用c.parse)。

    http://www.scala-archive.org/Expand-macros-before-typechecking-its-arguments-trees-td4641188.html

    Scala: macro to create an instance from a class body

    【讨论】:

    • 很好的解决方法,将表达式传递为String,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    相关资源
    最近更新 更多