Replace element in List with scala

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

    following is a simple example of String replacement in scala List, you can do similar for other types of data

        scala> val original: List[String] = List("a","b")
    
        original: List[String] = List(a, b)
    
        scala> val replace = original.map(x => if(x.equals("a")) "c" else x)
    
        replace: List[String] = List(c, b)
    

提交回复
热议问题