Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala package object getClass

Tags:

java

scala

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

app/package.scala:

package object app {
}

app/Main.scala:

package app

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

Compilation fails with:

object getClass is not a member of package app Note that app extends Any, not AnyRef. Such types can participate in value classes, but instances cannot appear in singleton types or in reference comparisons.

like image 301
mixel Avatar asked Sep 02 '16 07:09

mixel


2 Answers

You can define method inside app returning class:

package object app {
  def cls = getClass
}
like image 72
Nyavro Avatar answered Sep 27 '22 23:09

Nyavro


Thanks to Nyavro for the answer.

It seems that package object restricts access to its built-in member from outside and to get full access to package object as to plain object we can do following:

package object app {
  val instance = this
}

and use it like:

app.instance.getClass
like image 34
mixel Avatar answered Sep 27 '22 23:09

mixel