This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js and have Paul Jensen on-line!
See this thread for details.
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Lambda Expressions (The difference between)  RSS feed

 
Omar Dawod
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Folks,

This is my first day in Lambda world.

And I cannot understand why this code works:
new JButton().addActionListener(e -> {System.err.println("Hello from lambda");});

And this doesn't:
new Thread(r -> {System.err.println("Hello from lambda");}).start();

What is the difference???

Thanks!

Omar
 
Rob Spoor
Sheriff
Posts: 21048
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I understand lambda expressions correctly, the e in the action listener is the argument to the actionPerformed method. The r would then be the argument to the run method, but it doesn't take any arguments. Check out http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#target-types-and-method-arguments on how to do this.
 
Luan Cestari
Ranch Hand
Posts: 172
C++ Redhat Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Omar,

The point here is what 'e' is (and what would be 'r' in that case). The 'e' would be the ActionListener method's parameter, so you could use it in your Lambda Expression. In the Runnable interface, the method 'run' doesn't have parameters, so only '()' identifier would be allowed. Below some documentation of Lambda Expression (JSR 335) that may help:

http://cr.openjdk.java.net/~dlsmith/jsr335-0.6.1/B.html
http://download.oracle.com/otndocs/jcp/lambda-0_6_1-edr3-spec/index.html

Best Regards! =)

Luan
 
Omar Dawod
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys!

Of course it's the method argument... How couldn't I see that
Thank you guys and have a great weekend.

Kind Regards
Omar
 
Cay Horstmann
author
Ranch Hand
Posts: 195
22
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, you don't even need the braces:

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!