加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 08:43:24 所属栏目:安全 来源:网络整理
导读:如果调用过滤器返回空列表并返回过滤后的列表,如何返回原始的未过滤列表? scala val l = List(1,2,3)scala l.filter(_ == 4)res1: List[Int] = List() // would like this to be List(1,3)scala l.filter(_ == 3)res: List[Int] = List(3) // want to maint
如果调用过滤器返回空列表并返回过滤后的列表,如何返回原始的未过滤列表?

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

解决方法

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

scala> val l = List(1,3)
l: List[Int] = List(1,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,3)

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读