How to yield a single element from for loop in scala?

Posted by Julio Faerman on Stack Overflow See other posts from Stack Overflow or by Julio Faerman
Published on 2012-11-12T12:13:40Z Indexed on 2012/11/15 23:00 UTC
Read the original article Hit count: 113

Filed under:

Much like this question:

Functional code for looping with early exit

Say the code is

def findFirst[T](objects: List[T]):T = {
  for (obj <- objects) {
    if (expensiveFunc(obj) != null) return /*???*/ Some(obj)
  }
  None
}

How to yield a single element from a for loop like this in scala?

I do not want to use find, as proposed in the original question, i am curious about if and how it could be implemented using the for loop.

* UPDATE *

First, thanks for all the comments, but i guess i was not clear in the question. I am shooting for something like this:

val seven = for {
    x <- 1 to 10
    if x == 7
} return x

And that does not compile. The two errors are: - return outside method definition - method main has return statement; needs result type

I know find() would be better in this case, i am just learning and exploring the language. And in a more complex case with several iterators, i think finding with for can actually be usefull.

Thanks commenters, i'll start a bounty to make up for the bad posing of the question :)

© Stack Overflow or respective owner

Related posts about scala