Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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());
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...