Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

scala

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

package object domain { object Foo }  domain$.MODULE$.Foo$.MODULE$ 
like image 488
Frédéric Nowak Avatar asked Dec 29 '10 10:12

Frédéric Nowak


People also ask

What is a package object in Scala?

Scala 2 provides package objects as a convenient container shared across an entire package. Package objects can contain arbitrary definitions, not just variable and method definitions. For instance, they are frequently used to hold package-wide type aliases and implicit conversions.

How do I use Scala packages?

Click on file, new then scala project and give it a name. To define a package in Scala you use the keyword package that is then followed by name of the package. To package your code you create a Scala object (. scala) and place it there then store it in your preferred folder in project structure.

Is everything an object in Scala?

Not everything is an object in Scala, though more things are objects in Scala than their analogues in Java. The advantage of objects is that they're bags of state which also have some behavior coupled with them. With the addition of polymorphism, objects give you ways of changing the implicit behavior and state.


1 Answers

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.

like image 75
Steve Avatar answered Oct 13 '22 01:10

Steve