scala中的静态内部类 [英] Static inner classes in scala
问题描述
Scala中使用Java进行此类操作的模拟是什么:
What is the analog in Scala of doing this in Java:
public class Outer {
private Inner inner;
public static class Inner {
}
public Inner getInner() { return inner; }
}
我特别希望我的内部课程不必须有一个完全限定的名称 - 即我想要 Trade.Type
,而不是 TradeType
。所以在Scala我想象它可能是这样的:
I specifically want my inner class to not have to have a fully qualified name - i.e. I want Trade.Type
, not TradeType
. So in Scala I imagined it might be something like:
class Outer(val inner: Inner) {
object Inner
}
但这似乎不起作用:我的scala 外部
类外部看来,内部似乎不可见。一个解决方案当然是:
But this doesn't seem to work: my scala Inner
just doesn't seem to be visible from outside the Outer
class. One solution would of course be:
class Inner
class Outer(val inner: Inner)
哪个好 - 但由于我的班级名称,内部
实际上是 Outer
的类型,而 Outer
实际上有一个长名称。所以:
Which is OK - but because of the names of my classes, Inner
is really the "type" of the Outer
and Outer
actually has a long name. So:
class SomeHorriblyLongNameType
class SomeHorriblyLongName(myType: SomeHorriblyLongNameType)
这是冗长而可怕的。我可以用 Type
替换 SomeHorriblyLongNameType
但是它与它与之相关的类之间没有明显的连接。 Phew
Which is verbose and horrible. I could replace SomeHorriblyLongNameType
with just Type
but there would then be no obvious connection between it and the class it was related to. Phew
推荐答案
如果不需要访问内部类中的外部类,你可以这样做(你不会鉴于你的内部类被声明为 static
),所以在Java中没有:
You can do something like this if don't need access to the outer class in the inner class (which you wouldn't have in Java given that your inner class was declared static
):
object A{
class B {
val x = 3
}
}
class A {
// implementation of class here
}
println(new A.B().x)
这篇关于scala中的静态内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!