Reputation: 179
I have an immutable Seq. I need to create a new Seq from it, with only one element changed, whose index is given to me. How can I do it ? (I think since the sequence is immutable I will need to use some function and create a new output sequence, but I do not know how to check index for conditional update in the "map" function.) Thanks
Upvotes: 2
Views: 1060
Reputation: 48400
If the element has to be transformed with some function f
then
val idx = 2 // given index to transform
mySeq.iterator.zipWithIndex.map {
case (e, `idx`) => f(e)
case (e, _) => e
}.toSeq
If it just needs to be replaced with another given element then
mySeq.updated(idx, newElement)
If collection will be frequently updated then consider Vector
instead because List
which is the default implementation of Seq
is not optimised for updates.
Upvotes: 3