40

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
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
user786045
  • 2,498
  • 4
  • 22
  • 18
  • 2
    possible duplicate of [How can I pass a Scala object reference around in Java?](http://stackoverflow.com/questions/3845737/how-can-i-pass-a-scala-object-reference-around-in-java) – om-nom-nom Sep 05 '12 at 14:55

2 Answers2

60

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());
    }
}
Community
  • 1
  • 1
Petr
  • 62,528
  • 13
  • 153
  • 317
  • 4
    This doesn't really work either. Eclipse tells me: **Person$ cannot be resolved to a variable'code** and the code doesn't compile – user786045 Sep 05 '12 at 15:06
  • 5
    @user786045, you need to add an import statement for Person$ manually. Eclipse does not add it automatically on "organize imports". – Hendrik Brummermann Nov 07 '14 at 14:15
1

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);
}
SerCe
  • 5,826
  • 2
  • 32
  • 53