1

In "Programming in scala" it is stated that lists are immutable and arrays are mutable. But I can't change the array length -- neither can I with list, so in this way they are both immutable. I can change array's element value -- just setting a new one, and I can modify a list's element value with, say, map method. So in this way they are both mutable.

So why arrays are considered to be mutable and lists not?

3 Answers 3

10

First, it's important to know that Scala actually has both mutable and immutable collections. If you use scala.collection.mutable.ListBuffer, it will (as the name indicates) be mutable. If you use scala.collection.immutable.List it will not be.

Second, the map function does not alter the elements of the list, rather, it creates an entirely new list containing the result of the map function applied to each element of the start list, for example:

var l1 = List(1,3,5)
var l2 = l1.map( _ + 2 )
println(l1) // List(1, 3, 5)
println(l2) // List(2, 4, 6)

l2 now contains a new list, entirely separate from l1, and l1 has not been changed.

Sign up to request clarification or add additional context in comments.

1 Comment

There's no scala.collection.mutable.List.
3

You can't transform the elements of a List - if you use a function which transforms the elements a new List is created:

scala> val xs = List(1,2,3)
xs: List[Int] = List(1, 2, 3)

scala> xs.map(_+1)
res0: List[Int] = List(2, 3, 4)

scala> xs
res1: List[Int] = List(1, 2, 3)

In contrast, the elements of an Array are mutable:

scala> val xs = Array(1,2,3)
xs: Array[Int] = Array(1, 2, 3)

scala> xs(0) = 5

scala> xs
res3: Array[Int] = Array(5, 2, 3)

scala> val xs = List(1,2,3)
xs: List[Int] = List(1, 2, 3)

scala> xs(0) = 5
<console>:9: error: value update is not a member of List[Int]
              xs(0) = 5
              ^

Nevertheless you can't change the size of an array. If you want to do this you have to use scala.collection.mutable.Buffer:

scala> val xs = Array(1,2,3)
xs: Array[Int] = Array(1, 2, 3)

scala> xs += 4
<console>:9: error: reassignment to val
              xs += 4
                 ^

scala> val xs = collection.mutable.Buffer(1,2,3)
xs: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 2, 3)

scala> xs += 4
res6: xs.type = ArrayBuffer(1, 2, 3, 4)

Comments

1

List's map method will create a new list.

If you want to use a mutable collections see * scala.collection.mutable package.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.