来自Java代码的嵌套Scala单例 [英] Nested Scala singletons from Java code

查看:161
本文介绍了来自Java代码的嵌套Scala单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Scala(2.8)代码:

I have the following Scala (2.8) code:

object A {
  val message = "hello"
  object B {
    val message = "world"
  }
}

和类似的Java类:

public class C {
  public static String message() {
    return "HELLO";
  }
  public static class D {
    public static String message() {
      return "WORLD";
    }
  }
}

这些像我一样工作期待我从Scala打电话给他们:

These work as I'd expect when I call them from Scala:

scala> A.message  
res0: java.lang.String = hello

scala> A.B.message
res1: java.lang.String = world

scala> C.message  
res2: java.lang.String = HELLO

scala> C.D.message
res3: java.lang.String = WORLD

但是当我尝试类似的东西时从Java开始,编译器不喜欢第二行:

But when I try something similar from Java, the compiler doesn't like the second line:

System.out.println(A.message());
System.out.println(A.B.message()); // cannot find ... symbol  : variable B ...
System.out.println(C.message());
System.out.println(C.D.message());

当我用查看类文件时,很清楚为什么会出现这种情况javap的。我知道我可以使用

It's clear why this is the case when I look at the class files with javap. I know I can use

System.out.println(A$B$.MODULE$.message());

相反,或添加类似 val getB = B 到我的 A 对象并用

instead, or add something like val getB = B to my A object and replace the second line with

System.out.println(A.getB().message());

是否有一种标准方法可以使用Java代码中嵌套的Scala单例对象?

Is there a standard way to use nested Scala singleton objects from Java code?

推荐答案

我对Scala知之甚少,但考虑到 Scala编译成字节码的方式,我想你已经暴露了你唯一的两个选项。

I'm have little knownledge of Scala, but considering the way Scala is compiled into bytecode, I think you have exposed the only two options you have.

这篇关于来自Java代码的嵌套Scala单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆