Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

lambda Expression variables  RSS feed

 
Freiza Gen
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I know this code will not work because "result" needs to be final or effective final and must not be changed inside lambda.
Is there any way I can retrieve value of result variable after button.setOnAction?
 
Esteban Herrera
author
Ranch Hand
Posts: 42
1
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Freiza,

If you use a reference to an object and you don't create a new object using that reference inside the lambda expression, you can do what you want.

You can even use an array if you don't want to create a class just for that, for example:
 
Paul Clapham
Sheriff
Posts: 22823
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Although you should be aware the the value printed in line 7 of Esteban's code will be the value which was set in line 1; the code inside the lambda (lines 3 to 5) may never be executed, and if it is then it will be executed at a later time, after the code in the fragment has already completed.
 
Freiza Gen
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Esteban Herrera, very nice solution.

Thank You Paul Clapham for the advice.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!