我有一个类型 resultType
的 Context.this.type#c#universe#Type
.我需要将它与 Unit
匹配类型。我试过
resultType match {
case q"Unit" => ...
}
但我想
Unit
这里只是一个字符串文字,显然不匹配。如何通过 quasiqotes 匹配类型?我也试过
resultType match {
case TypeRef(ThisType(_), Symbol("scala.Unit"), _) => ...
}
但有一个错误:
[error] pattern type is incompatible with expected type;
[error] found : Symbol
[error] required: Context.this.c.universe.SymbolContextApi
如何以这种方式匹配类型?
最佳答案
在这种情况下,quasiquotes 不起作用的主要原因是您在 Tree
上不匹配。而是一个 Type
.这两个是反射 API 的独立概念,并不完全相同。
检查类型是否与您期望的相同的一种简单方法是使用 typeOf
并输入相等运算符 =:=
:
case tpe if tpe =:= typeOf[Unit] =>
当然,这不是唯一的方法。也可以通过
TypeRef
匹配并检查其中的符号是否相等,如其他答案所示。
关于scala - 如何通过 quasiquotes 或 deconstructors 匹配 `universe#Type`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18735295/