简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM