停止在 Scala 中处理地图 [英] Stop processing maps in Scala

查看:33
本文介绍了停止在 Scala 中处理地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,如果元素= 2,我需要停止处理地图:

In the following code, I need to stop processing the map if the element = 2:

val seq = Seq(1,2,3)

seq.map { x => if (x==2) /* stop processing the map */  }

这可能吗?

推荐答案

你不能直接用 map() 来做,因为 map() 被设计成工作在整个集合中,但您可以将集合分成 2 部分,并将 map() 应用于其中一个而不是另一个.

You can't do it with map() directly as map() is designed to work over the entire collection, but you can split the collection into 2 parts and apply the map() to one and not the other.

val seq = Seq(0,1,2,3,3,2,1,0)
val (before, after) = seq.span(_ != 2)
before.map(_ + 70) ++ after  //res0: Seq[Int] = List(70, 71, 2, 3, 3, 2, 1, 0)

这篇关于停止在 Scala 中处理地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆