wmebrek
wmebrek

Reputation: 33

JAVA - Instantiate Scala case class

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

Upvotes: 3

Views: 1801

Answers (1)

Mario Galic
Mario Galic

Reputation: 48410

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).

Upvotes: 5

Related Questions