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
^
The easiest way to replace an item in a list is to use the Python indexing syntax . Indexing allows you to choose an element or range of elements in a list. With the assignment operator, you can change a value at a given position in a list.
Replace a specific string in a list. If you want to replace the string of elements of a list, use the string method replace() for each element with the list comprehension. If there is no string to be replaced, applying replace() will not change it, so you don't need to select an element with if condition .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With