在Scala中将map和filter的组合归零

栏目: Scala · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/8938916/combination-of-map-and-filter-nulls-out-in-scala
是否可以通过一次调用表示map和null跳过来表达以下代码?
list.map(_.accept(this, arg).asInstanceOf[T]).filter(_ != null)
list flatMap { i => Option(i.accept(this, arg).asInstanceOf[T]) }

或者,如果您愿意,(尽管这会或多或少地转换为您的原始表达)

for {
  item <- list
  itemConverted = item.accept(this, arg).asInstanceOf[T]
  itemNonNull = itemConverted if itemConverted != 0
} yield itemNonNull

使用collect是可能的,但由于部分函数的isDefinedAt测试,它可能会在大多数参数上调用accept两次:

list collect {
  case i if i.accept(this, arg).asInstanceOf[T] != null => i.accept(this, arg).asInstanceOf[T]
}

人们需要使用一些记忆(或智能提取器)来避免这种情况.

翻译自:https://stackoverflow.com/questions/8938916/combination-of-map-and-filter-nulls-out-in-scala


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Impractical Python Projects

Impractical Python Projects

Lee Vaughan / No Starch Press / 2018-11 / USD 29.95

Impractical Python Projects picks up where the complete beginner books leave off, expanding on existing concepts and introducing new tools that you’ll use every day. And to keep things interesting, ea......一起来看看 《Impractical Python Projects》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具