Scala getClass package object

I want to get java.lang.Class for a Scala package object:

Application / package.scala:

 package object app { } 

Application / Main.scala:

batch application

 object Main extends App { val _ = app.getClass } 

Fail compilation:

The getClass object is not part of the batch application. Note that the application extends Any, not AnyRef. Such types can participate in value classes, but instances cannot be displayed in singleton types or in comparison links.

+5
source share
2 answers

You can define a method inside the returned class of the application:

 package object app { def cls = getClass } 
+2
source

Thanks Nyavro for the answer.

It seems that the package object restricts access to its built-in member from the outside and to get full access to the package object, like ordinary objects, which we can do as follows:

 package object app { val instance = this } 

and use it like:

 app.instance.getClass 
+2
source

All Articles