Scala: Can there be any reason to prefer `filter+map` over `collect`?

前端 未结 3 1946
猫巷女王i
猫巷女王i 2021-02-05 01:34

Can there be any reason to prefer filter+map:

list.filter (i => aCondition(i)).map(i => fun(i))

over collect?

3条回答
  •  走了就别回头了
    2021-02-05 01:59

    One case where filter/map looks cleaner is when you want to flatten the result of filter

    def getList(x: Int) = {
      List.range(x, 0, -1)
    }
    
    val xs = List(1,2,3,4)
    
    //Using filter and flatMap
    xs.filter(_ % 2 == 0).flatMap(getList)
    
    //Using collect and flatten
    xs.collect{ case x if x % 2 == 0 => getList(x)}.flatten
    

提交回复
热议问题