java利用嵌套类实现单例,来自Java代码的嵌套Scala单例

I have the following Scala (2.8) code:

object A {

val message = "hello"

object B {

val message = "world"

}

}

And a similar Java class:

public class C {

public static String message() {

return "HELLO";

}

public static class D {

public static String message() {

return "WORLD";

}

}

}

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

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

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

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

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

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

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值