How the get the classOf for a scala object type

Scala

Scala Problem Overview


I wonder how to get a class object for an object type in Scala. Ok, that is a mouth full because of the double meaning for object. So here an example which will fail:

object Main
{
   private [this] val TAG = classOf [Main].getName;
} // Main

If Main was class it works perfectly. Any ideas?

Scala Solutions


Solution 1 - Scala

scala> Main.getClass
res1: java.lang.Class[_] = class Main$

Solution 2 - Scala

The reason why classOf[Main] doesn't work is because Main is not a type.

Classes and traits define types, objects do not.

Solution 3 - Scala

Since Main is an object, for your example to work, simply replace your assignment line with;

private [this] val TAG = this.getClass.getName;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartinView Question on Stackoverflow
Solution 1 - ScalaAlexey RomanovView Answer on Stackoverflow
Solution 2 - ScalaJesperView Answer on Stackoverflow
Solution 3 - ScalaJoachim IsakssonView Answer on Stackoverflow