简体   繁体   English

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

[英]How to check if WeakTypeTag or Type represents concrete type?

How do I check if WeakTypeTag or Type represents concrete type? 如何检查WeakTypeTagType表示具体类型? This would be especially useful in macros, where I could use it to raise compilation error when type given by the user is not concrete: 这在宏中特别有用,在用户给出的类型不具体时,我可以使用它来引发编译错误:

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
}

I think this will do the trick: 我认为这样可以解决问题:

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

then 然后

scala> macroMethod[Int]

scala> class C[T] { macroMethod[T] }
<console>:10: error: You must provide concrete type.
       class C[T] { macroMethod[T] }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查反射类型是否表示一个元组? - How to check if reflected Type represents a tuple? 在 scala 宏中,如何从 WeakTypeTag 中检索完整的类型信息? - In scala macro, how to retrieve full type information from a WeakTypeTag? 在Scala宏注释中获取给定类型的WeakTypeTag - Obtaining a WeakTypeTag for a given type in a Scala macro annotation 如何在Haskell中定义代表单位类型的类型? - How to define a type that represents a Unit type in Haskell? 类型参数与 WeakTypeTag 反射 + quasiquoting 不匹配(我认为!) - type parameter mismatch with WeakTypeTag reflection + quasiquoting (I think!) 在scala反射中,如何解析具体类型成员? - In scala reflection, how to resolve concrete type member? 如何获得AST表示的值的类型? - How does one obtain the type of the value that an AST represents? 在需要具体类型的情况下,如何使用存在类型的变量? - How to use a variable with existential type where a concrete type is required? Scala中某个抽象类型的类型参数对应的具体类型如何体现? - How to reflect concrete types that corresponds to the type parameters of an abstraction type in Scala? scala中是否存在表示当前类型的“SELF”类型? - Is there a “SELF” type in scala that represents the current type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM