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

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")
Sign up to request clarification or add additional context in comments.

1 Comment

This works well for example for methods, but if you define some trait in package object you won't be able to reference it from Java this way.
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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.