如何检查WeakTypeTag或Type是否代表具体类型?

时间:2013-04-09 09:17:26

标签: scala reflection scala-macros

如何检查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
}

1 个答案:

答案 0 :(得分: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] }