WolfmanDragon WolfmanDragon - 1 year ago 68
Java Question

What reason is there for C# or Java having lambdas?

What reason is there for C# or java having lambdas? Neither language is based around them, it appears to be another coding method to do the same thing that C# already did.

I'm not being confrontational, if there is a reason I would like to know the reason why. For the purpose of full disclosure I am a Java programmer with a C++ background with no lisp experience, I may just be missing the point.


There are common use-cases which require passing (or storing) a block of code to be executed later. The most common would be event listeners. Believe it or not, the following bit of code uses a lambda-ish construct in Java:

JButton button = new JButton("Push me!");
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

The anonymous inner-class is acting as a lambda, albeit an extremely verbose one. With a little bit of implicit conversion magic, we can write the following equivalent in Scala:

val button = new JButton("Push me!")
button.addActionListener { e =>

C# makes this sort of thing fairly easy with delegates and (even better) lambdas.