简体   繁体   English

Scala:scalac中的file.class和file $ .class之间的区别

[英]Scala: Difference between file.class and file$.class from scalac

When I use scalac to compile file.scala, I end up with 2 outputs, file.class and file$.class. 当我使用scalac编译file.scala时,最终得到2个输出,即file.class和file $ .class。 What is the difference between these files and which is the appropriate one to then run? 这些文件之间有什么区别,什么是适合运行的文件? I get distinctly different error messages between executing "scala file" vs "scala file$". 我在执行“ scala文件”与“ scala file $”之间收到截然不同的错误消息。

Scala object s get compiled to classes ending in "$" because you're allowed to have an "ordinary" class with the same name. Scala object被编译为以“ $”结尾的类,因为允许您使用一个具有相同名称的“普通”类。 But the object's methods are also exposed as static methods on the "ordinary" class, so that they can be called under the names you would expect. 但是对象的方法在“普通”类中也作为静态方法公开,因此可以在您期望的名称下调用它们。 This is an artifact of trying to represent the scala semantics in a way that make sense to Java / the JVM, and I would encourage you to regard it as an implementation detail rather than something important. 这是一种尝试以对Java / JVM有意义的方式表示scala语义的构件,我鼓励您将其视为实现细节,而不是重要的东西。

(@MattPutnam's answer is correct that anonymous classes, including closures, are compiled to class files with $es in their name, but that's not what's causing your file$.class in this particular instance) (@MattPutnam的答案是正确的,匿名类(包括闭包)被编译为名称中带有$ es的类文件,但这并不是导致您的file $ .class在此特定实例中产生的原因)

Use scala file . 使用scala file If you're interested in the implementation details you might also want to try java -cp /path/to/scala-library.jar file . 如果您对实现细节感兴趣,则可能还需要尝试java -cp /path/to/scala-library.jar file

file$.class is some inner anonymous class. file $ .class是一些内部匿名类。 In Java they're very explicit, but they can be easy to miss in Scala. 在Java中,它们非常明确,但是在Scala中很容易错过。 If you use any method that takes a function, there's an implicit anonymous class there. 如果使用任何带有函数的方法,则那里有一个隐式的匿名类。 Post the code and I'll point it out. 发布代码,我会指出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM