Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8819431
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T05:21:25+00:00 2026-06-14T05:21:25+00:00

Much like this question: Functional code for looping with early exit Say the code

  • 0

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 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T05:21:26+00:00Added an answer on June 14, 2026 at 5:21 am

    If you want to use a for loop, which uses a nicer syntax than chained invocations of .find, .filter, etc., there is a neat trick. Instead of iterating over strict collections like list, iterate over lazy ones like iterators or streams. If you’re starting with a strict collection, make it lazy with, e.g. .toIterator.

    Let’s see an example.

    First let’s define a “noisy” int, that will show us when it is invoked

    def noisyInt(i : Int) = () => { println("Getting %d!".format(i)); i }
    

    Now let’s fill a list with some of these:

    val l = List(1, 2, 3, 4).map(noisyInt)
    

    We want to look for the first element which is even.

    val r1 = for(e <- l; val v = e() ; if v % 2 == 0) yield v
    

    The above line results in:

    Getting 1!
    Getting 2!
    Getting 3!
    Getting 4!
    r1: List[Int] = List(2, 4)
    

    …meaning that all elements were accessed. That makes sense, given that the resulting list contains all even numbers. Let’s iterate over an iterator this time:

    val r2 = (for(e <- l.toIterator; val v = e() ; if v % 2 == 0) yield v)
    

    This results in:

    Getting 1!
    Getting 2!
    r2: Iterator[Int] = non-empty iterator
    

    Notice that the loop was executed only up to the point were it could figure out whether the result was an empty or non-empty iterator.

    To get the first result, you can now simply call r2.next.

    If you want a result of an Option type, use:

    if(r2.hasNext) Some(r2.next) else None
    

    Edit Your second example in this encoding is just:

    val seven = (for {
        x <- (1 to 10).toIterator
        if x == 7
    } yield x).next
    

    …of course, you should be sure that there is always at least a solution if you’re going to use .next. Alternatively, use headOption, defined for all Traversables, to get an Option[Int].

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an ajax loader much like this one: $('#loadingDiv') .hide() // hide it
I'm thinking about building a login system for Ruby on Rails, much like this
I want to do something like this, but I haven't had much success so
This feels like it should be pretty simple, but not much seems to be
I would like a hint or much better a solution for this: I do
I'd like to add custom controls to the mediaPlayer control view much as this
This could save me so much time. Sometimes I find myself writing things like
I need to create this layout and I'd like to do as much of
I'm asking a question very similar to this one —dare I say identical? An
This is a followup to this question. Here's the code I'm trying to understand

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.