St.Antario
St.Antario

Reputation: 27385

Understanding scala.collection.immutable.ListSet implementation

I'm looking at how scala.collection.immutable.ListSet[T] at 2.12 is implemented and have a question about how it works:

sealed class ListSet[A] extends AbstractSet[A]
  with Set[A]
  with GenericSetTemplate[A, ListSet]
  with SetLike[A, ListSet[A]]
  with Serializable {

  def +(elem: A): ListSet[A] = new Node(elem)

  //...

  protected class Node(override protected val elem: A) extends ListSet[A] with Serializable {
      override def +(e: A): ListSet[A] = if (contains(e)) this else new Node(e)
     //...
  }
}

As can be seen the Node.+(e: A) simply creates a new Node with the given element. How is the reference to the Node on which the + was invoked is retained? The next method is implemented as

override protected def next: ListSet[A] = ListSet.this

which should give us the reference to the initial empty ListSet instance.

Can you please explain how this works?

Upvotes: 0

Views: 73

Answers (1)

Harald Gliebe
Harald Gliebe

Reputation: 7564

Since Node is defined as an inner class of ListSet each instance of Node automatically contains a reference to the instance of the outer class it was created in.

You can access this instance of the outer ListSet from within the inner class with the expression ListSet.this

Upvotes: 4

Related Questions