How does Scala handle inner classes differently to Java's nested, static or non-static, classes?
问题:
回答1:
The major difference is that if you have
class Outer {
class Inner {
def foo(x: Inner): Inner = this // just for the example below
}
}
and two instances of Outer
:
val a = new Outer
val b = new Outer
then a.Inner
and b.Inner
are two different types (where in Java they'd both be Outer.Inner
), so that you can't do
val aInner = new a.Inner
val bInner = new b.Inner
aInner.foo(bInner)
They do have a common supertype which is written Outer#Inner
.
回答2:
Scala has proper nested classes, just like they were originally invented in Beta. Java's inner classes are not nested classes. The main difference is that nested classes are nested in the enclosing object, not merely an inner class inside the enclosing class. IOW: a nested class is a runtime instance property of an object of the enclosing class, and just like two different instances of the same class have identically named but different valued instance variables (fields), they also have identically named but different valued nested classes.
IOW, foo.SomeInnerClass
and bar.SomeInnerClass
are different classes and not type-compatible.