1

たとえば、次の形式でマクロを作成したいとします。

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

fnparamの型を と書くとc.Expr[=> Unit]、明らかにコンパイルエラーで失敗します。

を使用してscala 2.10.2います。そのようなマクロを実現する方法はありますか?

4

1 に答える 1

2

:のタイプを使用c.Expr[Any]および変更できます。fnc.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
于 2013-06-14T04:49:37.703 に答える