3

Given a method defined on a (3rd party, so I can't just move it) Scala package object, like so:

package foo

package object bar {
  def doSomething(s: String): String = ???
}

I need to call doSomething from Java code. I know that in general, I can get at a Scala companion object's methods from Java using ScalaObject$.method(). However, the example above compiles to foo.bar.package$.class, and of course Java screams about package being a reserved word.

Is there a way to call this from Java directly?

2 Answers 2

4

The best I can come up with (works, but ugly) is to wrap doSomething in Scala code that's not in a package object, and then call the wrapper from my Java code.

object BarUtil {
  def wrapper(s: String) = foo.bar.doSomething(s)
}

and in Java

public String doIt(String s) {
    return BarUtil$.wrapper(s);
}
3

You can access the package object as foo.bar.package$.MODULE$ (note the dollar signs, do not remove them):

foo.bar.package$.MODULE$.doSomething("hello")

Not the answer you're looking for? Browse other questions tagged or ask your own question.