I have seen samples of closure from – What is a 'Closure'?
Can anyone provide simple example of when to use closure?
Specifically, scenarios in which closure makes sense?
Lets assume that the language doesn’t have closure support, how would one still achieve similar thing?
Not to offend anyone, please post code samples in a language like c#, python, javascript, ruby etc.
I am sorry, I do not understand functional languages yet.
Closures are simply great tools. When to use them? Any time you like… As has already been said, the alternative is to write a class; for example, pre C# 2.0, creating a parameterised thread was a real struggle. With C# 2.0 you don’t even need the `ParameterizedThreadStart’ you just do:
Compare that to creating a class with a name and value
Or likewise with searching for a list (using a lambda this time):
Again – the alternative would be to write a class with two properties and a method:
This is fairly comparable to how the compiler does it under the bonnet (actually, it uses public read/write fields, not private readonly).
The biggest caveat with C# captures is to watch the scope; for example:
This might not print what you expect, since the variable i is used for each. You could see any combination of repeats – even 10 10’s. You need to carefully scope captured variables in C#:
Here each j gets captured separately (i.e. a different compiler-generated class instance).
Jon Skeet has a good blog entry covering C# and java closures here; or for more detail, see his book C# in Depth, which has an entire chapter on them.