Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a Scala singleton object in Java?

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
like image 565
user786045 Avatar asked Sep 05 '12 14:09

user786045


People also ask

Is Scala object a singleton?

Instead of static keyword Scala has singleton object. A Singleton object is an object which defines a single object of a class. A singleton object provides an entry point to your program execution. If you do not create a singleton object in your program, then your code compile successfully but does not give output.

Can I call Scala from Java?

A Scala trait with no method implementation is just an interface at the bytecode level and can thus be used in Java code like any other interface.

How can a singleton object be made executable in Scala?

Scala Singleton Object Singleton object is an object which is declared by using object keyword instead by class. No object is required to call methods declared inside singleton object. In scala, there is no static concept. So scala creates a singleton object to provide entry point for your program execution.

What is the difference between singleton object and companion object?

A singleton object named the same as a class is called a companion object. Also a companion object must be defined inside the same source file as the class.


2 Answers

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());     } } 
like image 96
Petr Avatar answered Sep 22 '22 22:09

Petr


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); } 
like image 40
SerCe Avatar answered Sep 26 '22 22:09

SerCe