有没有办法在scala宏中使用by-value参数?

时间:2013-06-14 04:17:24

标签: scala macros scala-2.10

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

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 param的类型写为c.Expr[=> Unit],它显然会因编译错误而失败。

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

1 个答案:

答案 0 :(得分:2)

您可以使用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
相关问题