比较 Scala 反射符号

Comparing Scala reflection Symbols

Types Scaladoc 页面警告:

Type Equality can be checked with =:=. It's important to note that == should not be used to compare types for equality-- == can't check for type equality in the presence of type aliases, while =:= can.

Symbols, but looking at the implementation 没有类似的警告,它似乎没有覆盖 equals。有没有办法比较符号是否相等(即它们是否代表相同的 Scala type/val/method/etc。)?

对于 TypeSymbols 我显然可以使用 .toType=:=,所以问题主要是关于 TermSymbols。

似乎 == 可以用于符号(在某种程度上)。我不想过度解释 scaladoc,但我认为别名对它们来说并不重要。 (我也希望关于符号的部分包含类似的警告。)

Symbols are used to establish bindings between a name and the entity it refers to, such as a class or a method. Anything you define and can give a name to in Scala has an associated symbol.

对比Type

As its name suggests, instances of Type represent information about the type of a corresponding symbol. This includes its members (methods, fields, type aliases, abstract types, nested classes, traits, etc.) either declared directly or inherited, its base types, its erasure and so on. Types also provide operations to test for type conformance or equivalence.

文档表明 Type 包含比 Symbol 更有价值的信息。

示例:

type L[A] = List[A]

scala> typeOf[L[String]].typeSymbol == typeOf[List[String]].typeSymbol
res47: Boolean = true

Symbol 相等,尽管 Type 不相等。因此,虽然 L[A]List[A] 具有不同的 Type 来自别名,但它们都解析为相同的 Symbol。内部类型信息似乎消失了,Symbol 似乎包含有关 List class 本身的信息。

scala> typeOf[List[String]].typeSymbol
res51: reflect.runtime.universe.Symbol = class List

scala> typeOf[L[String]].typeSymbol
res52: reflect.runtime.universe.Symbol = class List

所以它们是相等的:

scala> typeOf[L[String]].typeSymbol == typeOf[L[Int]].typeSymbol
res55: Boolean = true

虽然这些不是:

scala> typeOf[L[String]] =:= typeOf[L[Int]]
res56: Boolean = false

因此,虽然看起来基础类型应该具有相同的 Symbol,但 Symbol 可能不包含您进行上述完整比较所需的所有信息。