内容简介:翻译自: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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- python中将list转为dict
- Spring中将header头转换为参数
- 数组 – 如何在Swift中将数组拆分成两半?
- postgresql – 在postgres中将表列名更改为大写
- 如何在Java 8中将List转换为Map?
- 如何在Kubernetes中将Envoy用作负载均衡器
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
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》 这本书的介绍吧!