如果过滤函数导致空列表,则返回未过滤的列表

时间:2013-11-18 20:52:49

标签: scala

如果在其上调用filter返回空列表并返回已过滤的列表,如何返回原始的未过滤列表?

scala> val l = List(1,2,3)
scala> l.filter(_ == 4)
res1: List[Int] = List() // would like this to be List(1,2,3)
scala> l.filter(_ == 3)
res: List[Int] = List(3) // want to maintain this behavior

1 个答案:

答案 0 :(得分:2)

评论中已经提到了适当的答案。尽管如此,如果你不想打扰子类,你可以为这个乐趣写隐含的内容:

scala> val l = List(1,2,3)
l: List[Int] = List(1, 2, 3)

scala> case class ListFilter[T](list: List[T]) {
   def filterOrSelf(f: T => Boolean) = list.filter(f) match {
      case Nil => list 
      case l => l
   }
}
defined class ListFilter

scala> implicit def toListFilter[T](list: List[T]) = ListFilter(list)
toListFilter: [T](list: List[T])ListFilter[T]

scala> l.filterOrSelf(_ == 4)
res0: List[Int] = List(1, 2, 3)

scala> l.filterOrSelf(_ == 3)
res1: List[Int] = List(3)
相关问题