Lists are immutable in scala but then how can i do :: to a list to prepend a value in list?


How can i do :: to prepend a value in scala even though list belongs to the scala.collection.immutable ?

Thank you !!


The prepend function for immutable List creates another (immutable) List
and returns it. Just assign this result to a new val if you need further

For iterations you should use functional techniques like (tail)recursion or
map, flatMap and the like


Immutability of old list actually helps in creating new list in constant time. The new list is just one new object with two members:

  • head - containing the element you’ve added
  • tail - pointing to the list you’re prepending element to

Other immutable structures often work in similar fashion - new structure contains new elements plus references to old structures. For more information read: