scala - 比较 Scala 反射符号

标签 scala reflection scala-reflect

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.

文档表明,TypeSymbol 包含更有值(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/

相关文章:

scala - 如何发现未追踪的 future ?

java - 在 Java 中使用反射

Scala:反射和案例类

scala - 函数式风格提前退出深度优先递归

eclipse - 在 Eclipse 中与 JUnit 和 Scalatest 一起设置 Scala 项目

java - Java 中的抽象类和反射

java - 动态加载预编译类,无需反射

scala - 没有适用于案例类别类型的 TypeTag

scala - 在 scala 2 或 3 中,是否可以在运行时调试隐式解析过程?

scala - .sc 和 .scala 文件有什么区别?