Ska Ska - 1 year ago 25
Scala Question

How to replace a given item in a list?

This describes the problem pretty well:

scala> var l2 = List(1,2,3)
l2: List[Int] = List(1, 2, 3)

scala> l2(2) = 55
<console>:10: error: value update is not a member of List[Int]
l2(2) = 55

Answer Source

scala.List is immutable, meaning you cannot update it in place. If you want to create a copy of your List which contains the updated mapping, you can do the following:

val updated = l2.updated( 2, 55 )

There are mutable ordered sequence types as well, in scala.collection.mutable, such as Buffer types which seem 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 to note that some other answers have mentioned that you should use a "mutable List type" - this is true, but "List" in Scala just refers to the single-linked list, whereas in Java it's generally used for any ordered, random-access collection. There is also a DoubleLinkedList, which is more like a Java LinkedList, and a MutableList, which is a type used for the internals of some other types.

Generally speaking what you probably want in Scala is a Buffer for this job; especially since the default implementation is an ArrayBuffer, which is pretty close to being the same as ArrayList, most peoples' default, in Java.

If you ever want to find out what the closest "mapping" of a Java collections interface to the Scala world is, though, the easiest thing to do is probably just check what JavaConversions does. In this case you can see the mapping is to Buffer:

scala.collection.mutable.Buffer <=> java.util.List
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download