Raghav
Raghav

Reputation: 109

In Scala, List is Immutable But

I am a beginner to Scala language. In Scala, List is Immutable as per below code:

scala> var list = List(1,2,3,4,5)    // List created named ‘ list ’                                           

list: List[Int] = List(1, 2, 3, 4, 5)                                           

scala> 25 :: list // Prepend with Cons( :: ) , But here new list created.                                                        
res2: List[Int] = List(25, 1, 2, 3, 4, 5)

scala> list                        // print ‘  list ’   
res3: List[Int] = List(1, 2, 3, 4, 5)

But,

scala> list                                                                     
res1: List[Int] = List(1, 2, 3, 4, 5)                                           

scala> list :+= 12     // append list with :+=

scala> list                                                                     
res2: List[Int] = List(1, 2, 3, 4, 5, 12)

In above example, same "list" is appended. Then how list is immutable? It's confusing me. Any one kindly explain to me?

Upvotes: 2

Views: 453

Answers (1)

TessellatingHeckler
TessellatingHeckler

Reputation: 28993

http://daily-scala.blogspot.co.uk/2010/03/implicit-operator.html

:+= is not just appending, it's appending to a new list and reassigning the variable to point to the new list. It's equivalent to list = list + 12.

25 ++ list is making a new list, but not assigning it anywhere.

Upvotes: 1

Related Questions