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:
That isn't special Scala syntax, it's a method name. In Scala $ is a legal identifier. The method is inherited from the org. apache.
Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed.
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.
Although all answer that mention the Java reflection mechanism are correct this still doesnot solve the problem with the $ sign or the ".type" at the end of the class name.
You can bypass the problem of the reflection with the Scala classOf function.
Example:
println(classOf[Int].getSimpleName) println(classOf[Seq[Int]].getCanonicalName) => int => scala.collection.Seq => Seq
With this you just have the same result as you have in for example Java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With