I have a Scala object that I need to use in a Java class.
我有一个Scala对象,我需要在Java类中使用。
Here's the Scala object
这是Scala对象
object Person {
val MALE = "m"
val FEMALE = "f"
}
How can I use this Scala object in Java?
如何在Java中使用此Scala对象?
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
Person.MALE()//返回一个无用的String,因为我想要实际的Person对象
2 个解决方案
#1
41
Use Person$.MODULE$
. See also
使用Person $ .MODULE $。也可以看看
- How can I pass a Scala object reference around in Java?
- Singletons as Synthetic classes in Scala?
如何在Java中传递Scala对象引用?
单身作为Scala中的合成类?
Edit: A working example (I checked, it compiles and works): Scala:
编辑:一个工作示例(我检查,它编译和工作):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());
}
}
#2
0
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);
}
#1
41
Use Person$.MODULE$
. See also
使用Person $ .MODULE $。也可以看看
- How can I pass a Scala object reference around in Java?
- Singletons as Synthetic classes in Scala?
如何在Java中传递Scala对象引用?
单身作为Scala中的合成类?
Edit: A working example (I checked, it compiles and works): Scala:
编辑:一个工作示例(我检查,它编译和工作):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());
}
}
#2
0
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);
}