11

How to access an object Foo contained in a scala package object from Java?

package object domain { object Foo }  domain$.MODULE$.Foo$.MODULE$ 
Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106

2 Answers2

5

Perhaps this has changed as of Scala 2.8.1, but the proposed domain$Foo$.MODULE$ doesn't work. You have to use domain.package$Foo$.MODULE$.

And it's a little different for objects, methods, etc. Given the scala class:

package object domain {
  object foo
  def bar = 42
  val baz = 1.0
}

You can access foo, bar and baz in Java like:

domain.package$foo$.MODULE$
domain.package$.MODULE$.bar()
domain.package$.MODULE$.baz()

While I was trying to figure this out, I thought we were in trouble because Scala generates a class named package, which of course you can't import in Java. Fortunately, we only need the package$ companion object, which you can import.

Steve
  • 3,038
  • 2
  • 27
  • 46
0

If you look at an object in an object in the Scala lib, e.g. scala.math.Ordering.Boolean, you can get it from Java using scala.math.Ordering$Boolean$.MODULE$. I see no reason why package objects shouldn't behave like normal objects in this regard, so your Foo instance should be domain$Foo$.MODULE$

Landei
  • 54,104
  • 13
  • 100
  • 195