Scala - How to replace given item of the list, myList(index) = “something else”?

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.

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 be = mutable. Buffer(1,2,3) b: scala.collection.mutable.

BufferInt = ArrayBuffer(1, 2, 3) scala> b(2) = 55 scala> be res1: scala.collection.mutable. BufferInt = 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.

This will do, thanks val updated = l2. Updated( 2, 55 ) – Ska Feb 23 at 17:53.

The List you are creating is immutable. Scala> val l = List(1,2,3) l: ListInt = List(1, 2, 3) scala> l. GetClass res3: java.lang.

Class_ = class scala.collection.immutable. $colon$colon Use a mutable List instead and you should be fine.

Thanks to both but that won't go as I'm working with existing API that has immutable list. I guess then I need to replace entire list be reconstructing it. – Ska Feb 23 at 17:25.

Your problem is that Lists in scala are immutable, you need to use a mutable list instead. Import scala.collection.mutable. Queue and use that instead.

Queue is a MutableList, so it should do what you want.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions