Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does memory management for Scala collections work?

I can't figure out the implementation of some operations for Scala's immutable sequences. I'll use this as an example:

def example: List[Int] = {
  val list0 = List.range(1,10)

  list0.tail
}

Once the function finishes executing list0 is now out of scope. Would list0's head be removed from memory, or would list0 stay the same until the entire list is garbage collected?

like image 360
user3599828 Avatar asked Sep 25 '15 22:09

user3599828


1 Answers

In your example, the head of list0 will be left to the garbage collector to collect, as nothing will reference it. The remaining items (the tail), however, will continue to exist upon exiting the function (provided the result of the call is assigned to something).

Each cell in a list maintains a reference to the next cell in the list (or to Nil), but not vice versa.

like image 115
kes Avatar answered Nov 10 '22 00:11

kes