How can I use a Scala singleton object in Java?

≯℡__Kan透↙ 提交于 2019-11-27 05:14:06
Petr Pudlák

Use Person$.MODULE$. See also


Edit: A working example (I checked, it compiles and works): Scala:

object Person {
  val MALE = "m";
}

Java counterpart:

public class Test {
    Person$ myvar = Person$.MODULE$;

    public static void main(String argv[]) {
        System.out.println(new Test().myvar.MALE());
    }
}

In case you use a package object, the access is a bit different

Scala:

package my.scala.package

package object Person {
  val MALE = "m";
}

Java counterpart:

public static void main() {
  System.out.println(my.scala.package.Person.package$.MODULE$.MALE);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!