简体   繁体   中英

Lambda expression syntax in java

I'm trying to understand how the "e" fits in the following lambda expression in java:

testButton.addActionListener(e -> System.out.println("Click Detected by Lambda Listner"));

Why is it an "e"? Shouldn't it be "()"?

e here is the name of the variable (parameter of the method), it could be anything. e is possibly of type ActionEvent , a () indicates a method with no parameters

The addActionListener method requires an ActionListener , which is an interface with a single method

 public void actionPerformed(ActionEvent e);

In Java 8, you can use a lambda expression to implement an interface with a single method like this one. The rule is that the lambda expression must have the same parameter types and return types as the method in the interface. The compiler can then convert the lambda expression into a class that implements the interface.

So in this particular case, you need a lambda expression that

  • has a single parameter - an ActionEvent
  • has void return type - that is, it doesn't return anything.

In e -> System.out.println("something"); , the e is the ActionEvent . You could only replace it with () if the single method in the interface had no parameters at all.

Since you are passing a single parameter to Lamda expression, it is not mandatory to have ()

If we pass more than one parameter or no parameter then () is mandatory have it.

I believe this Link will helpful about understanding lamda expression that related your question

Lambda expression in thread Runnable interface is function interface with only one run() method在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM