Why Inner Class in Scala is bound to Outer Class O

2019-09-20 05:12发布

问题:

I am not able to understand why Inner Class in Scala is bound to Outer Class Object and not to Outer Class itself like in Java ?. Can someone explain any logic behind it. Why Scala developers defined Inner Class in this way?

Please see example below

class Network
{
  class Member()
  {
    val contacts = new ArrayBuffer[Member]
  }
}


object checkInner extends App {

/// creating home network  
  val home = new Network
  val father = new home.Member
  val mom = new home.Member
  val sister = new home.Member

  father.contacts += mom
  father.contacts += sister

// creating neighbour network
  val neighbour = new Network
  val uncle = new neighbour.Member

  father.contacts += uncle  (this will throw error -> type mismatch; found :    
       checkInner.neighbour.Member required: checkInner.home.Member)
       ** but it will work in Java **
}

回答1:

Non static inner classes in Java have the exact same semantics as in inner classes in Scala. (take that with a grain of salt, the difference in the type systems of both languages may introduce some things that invalidates that statement but these are irrelevant to what I am about to explain).

Both in Java a inner (non-static) class contains a reference to the instance of the outer class that was used to create it. The syntax for instantiation of a inner class makes it very clear (Assume that the for the java case HashPerson is non-static inner class in ContainingClass):

ContainingClass container = new ContainingClass();
HashPerson william = container.new HashPerson("willy");

(taken from https://stackoverflow.com/a/4070777/480674)

notice how container is on the left of the .new, as if this .new were a member of container. In Scala same would be new container.HashPerson("willy"); and in both languages the HashPerson instance would depend on a instance of the outer class.

Roughly the only real difference between the two language regarding inner classes (that are non-static in the Java case) is that Scala has the concept of path-dependent types. But that is entire different answer.



标签: scala