scala.List is immutable, meaning you cannot update it in place. If you want to create a copy of your list that contains an updated mapping, you can do the following:
val updated = l2.updated( 2, 55 )
There are also modified ordered sequence types in scala.collection.mutable , such as Buffer types, which are more like what you want. If you try the following, you should have more success:
scala> import scala.collection._ import scala.collection._ scala> val b = mutable.Buffer(1,2,3) b: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 2, 3) scala> b(2) = 55 scala> b res1: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 2, 55)
Edit: just note that some other answers mentioned that you should use a “mutable list type” - this is true, but the “List” in Scala only refers to a singly linked list, whereas in Java it is usually used for any ordered collection with arbitrary access. There is also a DoubleLinkedList , which is more like a Java LinkedList and a MutableList , which is the type used for the internal components of some other types.
All in all, what you might want in Scala is the Buffer for this job; especially since the default implementation is an ArrayBuffer , which is almost the same as an ArrayList , the default for most people in Java.
If you ever want to find out what the closest “mapping” of the Java collections interface to the Scala world is, however, the easiest way to check is JavaConversions . In this case, you can see that the mapping is Buffer :
scala.collection.mutable.Buffer <=> java.util.List
Calum
source share