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 7704837
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T23:46:15+00:00 2026-05-31T23:46:15+00:00

As discussed in Eric Lippert’s blog post Closing over the loop variable considered harmful

  • 0

As discussed in Eric Lippert’s blog post Closing over the loop variable considered harmful, closing over the loop variable in C# can have unexpected consequences. I was trying to understand if the same “gotcha” applied to Scala.

First of all, since this is a Scala question, I’ll try explaining Eric Lippert’s C# example adding a few comments to his code

// Create a list of integers
var values = new List<int>() { 100, 110, 120 };

// Create a mutable, empty list of functions that take no input and return an int
var funcs = new List<Func<int>>();

// For each integer in the list of integers we're trying
// to add a function to the list of functions
// that takes no input and returns that integer
// (actually that's not what we're doing and there's the gotcha).
foreach(var v in values)
  funcs.Add( ()=>v );

// Apply the functions in the list and print the returned integers.
foreach(var f in funcs)
  Console.WriteLine(f());

Most people expect this program to print 100, 110, 120. It actually prints 120, 120, 120.
The issue is that the () => v function we add to the funcs list closes over the v variable, not v’s value. As v changes value, in the first loop, all the three closures we add to the funcs list “see” the same variable v, which (by the time we apply them in the second loop) has value 120 for all of them.

I’ve tried to translate the example code to Scala:

import collection.mutable.Buffer
val values = List(100, 110, 120)
val funcs = Buffer[() => Int]()

for(v <- values) funcs += (() => v)
funcs foreach ( f => println(f()) )
// prints 100 110 120
// so Scala can close on the loop variable with no issue, or can it?

Does Scala indeed not suffer from the same issue or have I just translated Eric Lippert’s code badly and have failed to reproduce it?

This behavior has tripped many a valiant C# developer, so I wanted to make sure there are no strange similar gotchas with Scala. But also, once you understand why C# behaves the way it does, the output of Eric Lippert’s example code kind of makes sense (it’s the way closures work, basically): so what is Scala doing differently?

  • 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-05-31T23:46:16+00:00Added an answer on May 31, 2026 at 11:46 pm

    Scala doesn’t have the same problem because v is not a var, it’s a val. Therefore, when you write

    () => v
    

    the compiler understands that it is supposed to produce a function that returns that static value.

    If instead you use a var, you can have the same problem. But it’s a lot clearer that this is the asked-for behavior, since you explicitly create a var, and then have the function return it:

    val values = Array(100, 110, 120)
    val funcs = collection.mutable.Buffer[() => Int]()
    var value = 0
    var i = 0
    while (i < values.length) {
      value = values(i)
      funcs += (() => value)
      i += 1
    }
    funcs foreach (f => println(f()))
    

    (Note that if you try funcs += (() => values(i)) you will get an out of bounds exception because you have closed over the variable i which, when you call, is now 3!)

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

Sidebar

Related Questions

I have essentially the same problem discussed here: http://khason.net/blog/dependency-property-getters-and-setters-in-multithreaded-environment/ public static readonly DependencyProperty MyPropertyProperty
I've been reading Eric Lippert's blog posts on Asynchrony in C# 5 ( part
This might be discussed elsewhere but I can't find it. I have a .Net
I have similar problem to one discussed here , but with stronger practical usage.
I suppose similar problem would have been discussed here, but I couldn't find it.
I know this subject was discussed here, but I really can't get this to
I have seen it discussed somewhere that the following code results in obj being
I understand this has been discussed before but since this post in late 2010
Discussed this with a developer as I suggested to use CodeIgniter framework over standard
As discussed elsewhere, NSTabView does not have a setBackgroundColor method and subclassing NSTabView and

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.