如果调用原始未过滤列表,如果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
Run Code Online (Sandbox Code Playgroud)
评论中已经提到了适当的答案。不过,如果您不想为子类烦恼,您可以为此乐趣编写隐式:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
748 次 |
| 最近记录: |