Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala break out of map

Tags:

scala

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

like image 682
user1809913 Avatar asked Oct 23 '15 02:10

user1809913


People also ask

How do you break a for loop in Scala?

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.

Why does Scala not have break and continue?

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.

What does the dotted line from the Block represent in Scala?

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.

What is a breakable keyword in Scala?

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.


1 Answers

No need to create intermediate stream/iterator/view.

Just call takeWhile first:

 ids.takeWhile(_ != targetId).map(getObject)
like image 124
Aivean Avatar answered Sep 23 '22 22:09

Aivean