Replace element in List with scala

后端 未结 7 1100
花落未央
花落未央 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:26

    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).

提交回复
热议问题