How can I use a Scala singleton object in Java?

前端 未结 2 1242
我在风中等你
我在风中等你 2020-11-30 12: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\"
}
         


        
相关标签:
2条回答
  • 2020-11-30 12:50

    Use Person$.MODULE$. See also

    • How can I pass a Scala object reference around in Java?
    • Singletons as Synthetic classes in Scala?

    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());
        }
    }
    
    0 讨论(0)
  • 2020-11-30 12:51

    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);
    }
    
    0 讨论(0)
提交回复
热议问题