为什么 Scala 在类名的末尾放置一个美元符号? [英] Why does Scala place a dollar sign at the end of class names?
问题描述
在 Scala 中,当您查询对象的类或类名时,您将在打印输出的末尾得到一个恶意美元符号 ("$
"):
In Scala when you query an object for either its class or its class name, you'll get a rogue dollar sign ("$
") at the tail end of the printout:
object DollarExample {
def main(args : Array[String]) : Unit = {
printClass()
}
def printClass() {
println(s"The class is ${getClass}")
println(s"The class name is ${getClass.getName}")
}
}
结果为:
The class is class com.me.myorg.example.DollarExample$
The class name is com.me.myorg.example.DollarExample$
当然,手动删除末尾的$
"很简单,但我想知道:
Sure, it's simple enough to manually remove the "$
" at the end, but I'm wondering:
- 为什么会在那里?;和
- 无论如何要配置 Scala"以省略它?
- Why is it there?; and
- Is there anyway to "configure Scala" to omit it?
推荐答案
您在这里看到的原因是 scalac 将每个 object
编译为两个 JVM 类.末尾带有 $ 的那个实际上是实现实际逻辑的真正的单例类,可能是从其他类和/或特征继承的.没有 $ 的是一个包含 static
转发器方法的类.我认为这主要是为了 Java 互操作.也因为你实际上需要一种在 Scala 中创建静态方法的方法,因为如果你想在 JVM 上运行一个程序,你需要一个 public static void main(String[] args)
方法作为入口点.
What you are seeing here is caused by the fact that scalac compiles every object
to two JVM classes. The one with the $ at the end is actually the real singleton class implementing the actual logic, possibly inheriting from other classes and/or traits. The one without the $ is a class containing static
forwarder methods. That's mosty for Java interop's sake I assume. And also because you actually need a way to create static methods in scala, because if you want to run a program on the JVM, you need a public static void main(String[] args)
method as an entry point.
scala> :paste -raw
// Entering paste mode (ctrl-D to finish)
object Main { def main(args: Array[String]): Unit = ??? }
// Exiting paste mode, now interpreting.
scala> :javap -p -filter Main
Compiled from "<pastie>"
public final class Main {
public static void main(java.lang.String[]);
}
scala> :javap -p -filter Main$
Compiled from "<pastie>"
public final class Main$ {
public static Main$ MODULE$;
public static {};
public void main(java.lang.String[]);
private Main$();
}
我认为您对此无能为力.
I don't think there's anything you can do about this.
这篇关于为什么 Scala 在类名的末尾放置一个美元符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!