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没有类似的警告,但是看看implementation ,它似乎没有覆盖 equals
。有没有办法比较符号是否相等(即它们是否代表相同的 Scala 类型/值/方法/等)?
对于TypeSymbol
我显然可以使用 .toType
和=:=
,所以问题主要是关于 TermSymbol
s。
最佳答案
似乎 ==
对于符号来说很好(在某种程度上)。我不想尝试过度解释 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.
与类型
:
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
包含更有值(value)的信息。
示例:
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
类本身的信息。
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
可能不包含上面所示的完整比较所需的所有信息。
关于scala - 比较 Scala 反射符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29343862/