【问题标题】:Is there a way to use by-value parameters in scala macros?有没有办法在 scala 宏中使用按值参数?
【发布时间】:2013-06-14 04:17:24
【问题描述】:

例如,我想用这种形式创建一个宏:

def debug(fn: => Unit): Unit = if (doDebug) fn else ()

我尝试了以下方法:

def debug(fn: => Unit): Unit = macro debugImpl
def debugImpl(c: Context)(fn: c.Expr[Unit]): c.Expr[Unit] = {
  if (doDebug) fn else reify(())
}

但它失败并出现编译错误:

macro implementation has wrong shape:
  required: (c: scala.reflect.macros.Context)(fn: c.Expr[=> Unit]): c.Expr[Unit]
  found   : (c: scala.reflect.macros.Context)(fn: c.Expr[Unit]): c.Expr[Unit]
  type mismatch for parameter fn: c.Expr[=> Unit] does not conform to c.Expr[Unit]
    def debug(fn: => Unit): Unit = macro debugImpl

如果我将fn 参数的类型写为c.Expr[=> Unit],它显然会因编译错误而失败。

我正在使用scala 2.10.2。有没有办法实现这样的宏?

【问题讨论】:

    标签: scala macros scala-2.10


    【解决方案1】:

    您可以使用c.Expr[Any] 并更改fn 的类型:c.Expr[Unit](fn.tree)

    def debug(fn: => Unit): Unit = macro debugImpl
    def debugImpl(c: Context)(fn: c.Expr[Any]): c.Expr[Unit] = {
      import c.universe.reify
      if (true) c.Expr[Unit](fn.tree) else reify(())
    }
    
    
    scala> debug( println("abc") )
    abc
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-18
      • 1970-01-01
      • 2013-04-16
      • 2016-01-05
      相关资源
      最近更新 更多