3

after few days of search, I need your help to solve my problem.

I have a java program and I want to call a library written in scala, the jar is in classpath.

Scala main class:

object Program{
  def main(args: Array[String]): Unit = {
    ...
  }

  case class Config(param1, param2) {

    def parseProgramFromFiles(){}
    ...

  }

}

I'm trying to instantiate Config using

Program.Config config = new Program.Config(param1, param2);

I got this error: java: package Program does not exist

Program is in default package

Thank you

1 Answer 1

5

Scala uses name mangling to encode various Scala types into Java namespaces

Scala types are often found inside of object values as a form of namespacing. Scala uses a $ delimiter to mangle these names. For example, given object Kennel { class Dog } the inner class name would become Kennel$Dog.

Hence try

new Program$Config("foo", "bar");

EDIT: Hmm...actually it seems new Program.Config("foo", "bar") should work as

javap -v Program$Config.class

gives

InnerClasses:
     public static #11= #10 of #2; //Config=class Program$Config of class Program
     public static #14= #13 of #2; //Config$=class Program$Config$ of class Program

and indeed on my machine given

package example

object Program {
  case class Config(param1: String, param2: String)
}

then

package example;

public class Main {
    public static void main(String[] args) {
        Program.Config config = new Program.Config("foo", "bar");
        System.out.println(config);
    }
}

outputs Config(foo,bar).

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your response, Intellij cannot resolve symbol Program$Config
Note that, typically in Scala, you would not construct an instance of a case class via the case class' constructor but rather by calling the companion object's apply method. In Java, that would look roughly like Program.Config$.apply(bla).
@JörgWMittag Program.Config$.MODULE$.apply("foo", "bar") seems to work.
I was able to instantiate the case class Config by updating the library and adding the package under name example for object Program and using Program.Config config = new Program.Config("foo", "bar"); Thank you for useful response.

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.