[英]Import Scala object within object in Java
I have an object within another object in Scala which I want to import in Java.我在 Scala 中的另一个 object 中有一个 object,我想将其导入 ZD52387880E1EA22817A872D375921。 The setup is something like this:
设置是这样的:
Scala: Scala:
package scalapart;
object Outer {
object Inner {
def method: String = "test"
}
}
Java: Java:
import scalapart.Outer.Inner;
...
Outer.Inner.method()
Unfortunately, I get cannot find symbol
in line 1 of the Java code.不幸的是,我在 Java 代码的第 1 行
cannot find symbol
。 And if I import scalapart.Outer;
如果我
import scalapart.Outer;
, then the second line reports the same issue. ,然后第二行报告相同的问题。
Is there a way to import a Scala object that is defined inside another Scala object in Java? Is there a way to import a Scala object that is defined inside another Scala object in Java?
You can either used it like this:您可以像这样使用它:
public static void main(String[] args) {
String mystr = Outer.Inner$.MODULE$.method();
System.out.println(mystr); // test
}
Or do a static import
and use it like this ( or similar):或者执行
static import
并像这样(或类似)使用它:
import static org.scala.snippets.Outer.Inner$.MODULE$;
// ...
String mystr = MODULE$.method();
Java doesn't have any direct equivalent to the singleton object, so for every Scala singleton object, the compiler creates a synthetic Java class with the same name plus a dollar sign appended at the end) for that object
and a static
field named MODULE$
to hold the single instance of the class. Java doesn't have any direct equivalent to the singleton object, so for every Scala singleton object, the compiler creates a synthetic Java class with the same name plus a dollar sign appended at the end) for that
object
and a static
field named MODULE$
保存 class 的单个实例。 So, to ensure there is only one instance of an object, Scala uses a static class holder.因此,为了确保只有一个 object 实例,Scala 使用 static ZA2F2ED4F8EBC2CBB4C21A29DZ4 支架。
Your disassembled code looks something like this:您的反汇编代码如下所示:
public final class Outer
{
public static class Inner$
{
public static final Inner$ MODULE$;
static {
MODULE$ = new Inner$();
}
public String method() {
return "test";
}
}
}
public final class Outer$ {
public static final Outer$ MODULE$;
static {
MODULE$ = new Outer$();
}
private Outer$() {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.