Replace element in List with scala

后端 未结 7 1127
花落未央
花落未央 2021-02-01 00:45

How do you replace an element by index with an immutable List.

E.g.

val list = 1 :: 2 ::3 :: 4 :: List()

list.replace(2, 5)
7条回答
  •  滥情空心
    2021-02-01 01:31

    You can use map to generate a new list , like this :

    @ list
    res20: List[Int] = List(1, 2, 3, 4, 4, 5, 4)
    @ list.map(e => if(e==4) 0 else e)
    res21: List[Int] = List(1, 2, 3, 0, 0, 5, 0)
    

提交回复
热议问题