“too few argument lists for macro invocation”

2019-08-13 23:10发布

问题:

Given the following code:

case class JetDim(dimension: Int) {
  require(dimension > 0)
}

object JetDim {
  def build(dimension: Int): Int = macro JetDimMacro.apply
}

and the macro that it calls:

def apply(dimension: Int): Int = macro applyImpl

def applyImpl(c: Context)(dimension: c.Expr[Int]): c.Expr[Int] = ...

I'm getting this compile-time error:

[error]  too few argument lists for macro invocation
[error]  def build(dimension: Int): Int = macro JetDimMacro.apply

Why?

回答1:

The macro keyword takes a method that should have a Context parameter as its first parameter list (and then however many Expr arguments in subsequent lists). In JetDim you're giving macro a method that itself has a macro implementation. This just isn't valid syntax—you can't "nest" macro like this. You'll need to either call JetDimMacro.apply directly (as a normal method call) in JetDim.build, or use macro JetDimMacro.applyImpl (which is more likely what you want).