Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
857 views
in Technique[技术] by (71.8m points)

reflection - Why does Scala place a dollar sign at the end of class names?

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}")
  }
}

This results with:

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:

  • Why is it there?; and
  • Is there anyway to "configure Scala" to omit it?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...