How can I use a Scala singleton object in Java?

2019-01-07 23:24发布

I have a Scala object that I need to use in a Java class.

Here's the Scala object

object Person {
  val MALE = "m"
  val FEMALE = "f"
}

How can I use this Scala object in Java?

I have tried the following so far without success (compile errors):

  • Person.MALE() //returns a String which is useless as I want the actual Person object

2条回答
SAY GOODBYE
2楼-- · 2019-01-07 23:46

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());
    }
}
查看更多
神经病院院长
3楼-- · 2019-01-07 23:57

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);
}
查看更多
登录 后发表回答