I am going through the
ListMap
class in
scala.collection.immutable
I am having trouble understanding how the next function works in the Node class (which represents an entry in the ListMap). This is the implementation of the next function.
override protected def next: ListMap[K, V1] = ListMap.this
What is ListMap.this here? How does it point to the next Node?
Looking at ListMap
, you will note that the Node
class is an inner class of ListMap
. As there are no static inner classes in Scala, this means that each Node
is bound to a parent instance of ListMap
. You can refer to that parent with its class name and this
, so that’s what happens in next
.
The only method that creates a new Node
is ListMap
's updated
. Called on an empty ListMap (new ListMap[K, V]
), it will create a Node
with that empty map as parent. Called on a node (which doesn’t override it), that node will be the parent, as it extends ListMap. So that way it creates a kind of linked list.
I’m not sure if there are any benefits compared to explicitly using a tail
or parent
field, beside not being able to specify null as parent. Maybe it has some performance implications?
1 Like
Nice explanation. Thank you. I think you are right about the benefit being “impossible null parent”. I am not sure if it can have performance benefits. Would be interesting to see if it does