gpt4 book ai didi

scala - 如何通过 quasiquotes 或 deconstructors 匹配 `universe#Type`?

转载 作者:行者123 更新时间:2023-12-04 23:02:54 24 4
gpt4 key购买 nike

我有一个类型 resultTypeContext.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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com