4

如何检查WeakTypeTagType表示具体类型?这在宏中特别有用,当用户给出的类型不具体时,我可以使用它来引发编译错误:

def macroMethod[T]: Unit = macro macroMethod_impl[T]

def macroMethod_impl[T: c.WeakTypeTag](c: Context): c.Expr[Unit] = {
  import c.universe._

  def isConcrete(tpe: Type) = ???

  if(!isConcrete(weakTypeOf[T])) {
    c.error(c.enclosingPosition, "You must provide concrete type.")
  }

  c.literalUnit
}
4

1 回答 1

1

我认为这可以解决问题:

def isConcrete(tpe: Type) = !tpe.typeSymbol.asType.isAbstractType

然后

scala> macroMethod[Int]

scala> class C[T] { macroMethod[T] }
<console>:10: error: You must provide concrete type.
       class C[T] { macroMethod[T] }
于 2013-04-09T10:17:34.737 回答