Replace element in List with scala

后端 未结 7 1103
花落未央
花落未央 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

    It can also be achieved using patch function as

    scala> var l = List(11,20,24,31,35)
    
    l: List[Int] = List(11, 20, 24, 31, 35)
    
    scala> l.patch(2,List(27),1)
    
    res35: List[Int] = List(11, 20, 27, 31, 35)
    

    where 2 is the position where we are looking to add the value, List(27) is the value we are adding to the list and 1 is the number of elements to be replaced from the original list.

提交回复
热议问题