How should I remove the first occurrence of an object from a list in Scala?

前端 未结 2 1018
再見小時候
再見小時候 2021-01-13 16:56

What is the best way to remove the first occurrence of an object from a list in Scala?

Coming from Java, I\'m accustomed to having a List.remove(Object o) method tha

2条回答
  •  粉色の甜心
    2021-01-13 17:52

    You can clean up the code a bit with span.

    scala> def removeFirst[T](list: List[T])(pred: (T) => Boolean): List[T] = {
         |   val (before, atAndAfter) = list span (x => !pred(x))
         |   before ::: atAndAfter.drop(1)
         | }
    removeFirst: [T](list: List[T])(pred: T => Boolean)List[T]
    
    scala> removeFirst(List(1, 2, 3, 4, 3, 4)) { _ == 3 }
    res1: List[Int] = List(1, 2, 4, 3, 4)
    

    The Scala Collections API overview is a great place to learn about some of the lesser known methods.

提交回复
热议问题