What are the differences between Scala’s inner cla

2019-05-06 18:47发布

问题:

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.



标签: java scala oop