I need to break out of a seq map when a condition is met something like this where foo
would return a list of objects where the size depends on how long it takes to find the targetId
def foo(ids: Seq[String], targetId: String) = ids.map(id => getObject(id)).until(id == targetId)
obviously the until method does not exist but I am looking for something that does the equivalent
The Scala break example is pretty easy to reason about. Again, here's the code: breakable { for (i <- 1 to 10) { println (i) if (i > 4) break // break out of the for loop } } // more code here ... In this case, when i becomes greater than 4, the break word (a method, actually) is reached.
The name Scala was coined from combining the two terms SCAlable and LAnguage. But one of the aspects to note about the language is the exclusion of the most basic flow constructs like Break and Continue. Do you have any idea why the Scalable Language has done this? No, you say! Well, worry not, In this article, we touch upon exactly this.
A dotted line from the block represents a change of program flow due to the break statement. The below figure shows the internals of how the “In loop code execution” functions in Scala. In the flowchart from Figure 2, there is a call to break function which in turn raises an exception.
The breakable “keyword” essentially catches the exception, and the flow of control continues with any other code that might be after the breakable block. Note that break and breakable aren’t actually keywords; they’re methods in scala.util.control.Breaks.
No need to create intermediate stream/iterator/view.
Just call takeWhile
first:
ids.takeWhile(_ != targetId).map(getObject)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With