Can I use the lambda everytime I would pass an object that implements an interface?
Like the example below:
JButton button = new JButton();
// Without Lambda
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Doing something.");
}
});
// With Lambda
button.addActionListener(e -> {
System.out.println("Doing something.");
});
Yes, due to the
JButton#addActionListener()method expecting aActionListenertype object. Because this method is expecting anActionListener, and the type has one implementable methodactionPerformed(ActionEvent e), we can substitute it with a lambda expression which as we can see needs a parameter value forActionEvent, so we reference it using the name you chosee, though can be anything the writer chooses (though note it should always be lowerCamelCase format as it fits into Java Conventions. But a single lowercase letter is usually easiest IMO).This also applies to methods that have more than a single parameter as well!
I hope I didn't make that sound to confusing.
Thanks for the answer, that helped me a lot. =)