• Post Reply Bookmark Topic Watch Topic
  • New Topic

lambda and variable  RSS feed

 
Cedric Bosch
Ranch Hand
Posts: 99
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ive difficulties understanding why the following doesn't compile when the arguments in the lambda expression are variables instead of fields.

The message given by my IDE is :

java: variable test1 is already defined in method main(java.lang.String[])


 
John Longer
Greenhorn
Posts: 16
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

In your code test1 and test2 variables are already declared in



You can access local variable in lambda body( if it is effectively final for Java 8 or just final for versions before Java 8),
but you can't redeclare variable (use same variable) , which was already declared in local scope.


Here you are re-declaring test1 and test2 variables again in your lambda expression

 
Dóra Takács
Ranch Hand
Posts: 39
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Heyho!

betterString(test3, test4, (test3, test4) -> true);//compiles


This works because you pass the betterString method the static variables test3 and test4, and then you pass two locally created variables, that are named exactly the same as your static variables.

If you remember constructors:

We had to use the this keyword because the local variable names are referenced by default in case of conflict. Something similar happens in your example.
test1 and test2 are local, but test3 and test4 are class variables.

Lambdas always redeclare the parameters you give them in the parantheses. Writing (test1, test2) is just a convenience for shortly writing (String test1, String test2).
 
Winston Gutkowski
Bartender
Posts: 10573
65
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cedric Bosch wrote:Ive difficulties understanding...

I'll leave the "functional" stuff to bods who know it better; but you can save yourself some typing by using the conditional operator instead of if at line 14, viz:
  return predicate.betterString(s1, s2) ? s1 : s2;

HIH

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