在Scala中将map和filter的组合归零
发布时间:2020-12-16 08:50:44 所属栏目:安全 来源:网络整理
导读:是否可以通过一次调用表示map和null跳过来表达以下代码? list.map(_.accept(this,arg).asInstanceOf[T]).filter(_ != null) 解决方法 list flatMap { i = Option(i.accept(this,arg).asInstanceOf[T]) } 或者,如果您愿意,(尽管这会或多或少地转换为您的原始
是否可以通过一次调用表示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] } 人们需要使用一些记忆(或智能提取器)来避免这种情况. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |