How do I return the original, unfiltered list if calling filter
on it returns an empty list and return the filtered list otherwise?
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
Appropriate answer was already mentioned in comments. Still, if you don't want to bother with subclasses, you can write implicit for this fun:
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With