Replace element in List with scala

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

    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)
    

提交回复
热议问题