Getting the class for Main in Scala
Question
If I create a singleton object Main
with no companion class, is there any way to get the class of that singleton? classOf[Main]
gives an error: "not found: type Main".
Solution
As it's an instance of a class, you can use the method Main.getClass
to pull this one off.
Behind the scenes, the JVM knows that Main
is an instance of a class named Main$
, and this can be accessed via Java reflection methods if necessary.
Having said all of that, there's usually very little need for reflection in Scala anyway, so you shouldn't really need this unless you're just after an interesting bit of theory.
OTHER TIPS
Singleton objects, aka modules, do not have a "class" as you cannot inherit from them. Think of singleton and class as opposite notions.
They do have a type though:
object Main
def test(a: Main.type): Unit = println("Got: " + a)
test(Main)