How to access an object Foo
contained in a scala package object from Java?
package object domain { object Foo } domain$.MODULE$.Foo$.MODULE$
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With