Replace element in List with scala

Solution 1:

If you want to replace index 2, then

list.updated(2,5)    // Gives 1 :: 2 :: 5 :: 4 :: Nil

If you want to find every place where there's a 2 and put a 5 in instead,

list.map { case 2 => 5; case x => x }  // 1 :: 5 :: 3 :: 4 :: Nil

In both cases, you're not really "replacing", you're returning a new list that has a different element(s) at that (those) position(s).

Solution 2:

In addition to what has been said before, you can use patch function that replaces sub-sequences of a sequence:

scala> val list = List(1, 2, 3, 4)
list: List[Int] = List(1, 2, 3, 4)

scala> list.patch(2, Seq(5), 1) // replaces one element of the initial sequence
res0: List[Int] = List(1, 2, 5, 4)

scala> list.patch(2, Seq(5), 2) // replaces two elements of the initial sequence
res1: List[Int] = List(1, 2, 5)

scala> list.patch(2, Seq(5), 0) // adds a new element
res2: List[Int] = List(1, 2, 5, 3, 4)