Would anyone be so kind to post the equivalent Java code for a closure like this one (obtained using C#) with anonymous inner classes?
public static Func<int, int> IncrementByN()
{
int n = 0; // n is local to the method
Func<int, int> increment = delegate(int x)
{
n++;
return x + n;
};
return increment;
}
static void Main(string[] args)
{
var v = IncrementByN();
Console.WriteLine(v(5)); // output 6
Console.WriteLine(v(6)); // output 8
}
Furthermore, can anyone explain how partial applications can be obtained if lexical closures are available and viceversa? For this second question, C# would be appreciated but it’s your choice.
Thanks so much.
There is no closure yet in Java. Lambda expressions are coming in java 8. However, the only issue with what you’re trying to translate is that it has state, which not something that lamba expressions will support i don’t think. Keep in mind, it’s really just a shorthand so that you can easily implement single method interfaces. You can however still simulate this I believe:
I have not tested this code though, it’s just meant as an example of what might possibly work in java 8.
Think of the collections api. Let’s say they have this interface:
And a method on java.util.Collection:
Now, let’s see that without closures:
Why not just write this:
Much more concise right?
Now introduce lambdas:
See how much nicer the syntax is? And you can chain it too (we’ll assume there’s an interface to do filtering which which returns boolean values to determine whether to filter out a value or not):