Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

c#

lambda

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.

like image 820
WolfmanDragon Avatar asked Oct 16 '08 18:10

WolfmanDragon


1 Answers

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) {
        System.out.println("Pressed!");
    }
});

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 =>
  println("Pressed!")
}

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

like image 154
Daniel Spiewak Avatar answered Oct 18 '22 08:10

Daniel Spiewak