2013-06-14 1 views
1

Например, я хочу создать макрос с помощью этой формы:Есть ли способ использовать параметры по значению в макросах scala?

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 

If I напишите тип fn param как c.Expr[=> Unit], он, очевидно, не справляется с ошибкой компиляции.

Я использую scala 2.10.2. Есть ли способ достичь такого макроса?

ответ

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 

 Смежные вопросы

  • Нет связанных вопросов^_^