什么是 ScalaSignature?

What is a ScalaSignature?

将 Scala 文件反编译为 Java 代码时,经常会遇到用 ScalaSignature 注释的 类。这些似乎只有一个注释值,一种经过某种编码的字符串。为什么 Scala 编译器会创建这样一个奇怪的结构,而不是在 class 文件中使用自定义的 Attribute

来自Storage of pickled Scala signatures in class files

The legacy method for storing signatures as attributes is simultaneously more elegant, more compact (about 15%) and simpler than that using annotations. However, to access the pickled signature in attributes requires obtaining and parsing the entire class file. Because annotations are recognized by the JVM, the new method allows retrieving pickled signature bytes directly from within a running Scala program by using Java reflection.

The new method is part of an ongoing development to write a good Scala reflection library. Java reflection views Scala programs in a simplified Java-centric way. To give a Scala-centric view of the reflected program, information provided by Java reflection must be completed with information found in Scala signatures. The legacy storage method would have required all class files to be parsed again — the JVM has parsed them already and exposes most of their content through reflection. The new storage method allows accessing pickled Scala signatures in the same way than other reflective information is obtained, making the new Scala reflection library simpler and faster.

Whilst the Scala reflection library will not be part of the 2.8 release, it is desirable that existing 2.8 class files are compatible with the new reflection library when it becomes available. Furthermore, since 2.8 class files are incompatible with those of 2.7 in any case, changing the method of storing signatures in 2.8 will not require another binary-incompatible class file format change shortly after.