• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

lambda and variable

 
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[])



 
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

 
Ranch Hand
Posts: 41
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).
 
Bartender
Posts: 10777
71
Hibernate Eclipse IDE 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
 
First, you drop a couch from the plane, THEN you surf it. Here, take this tiny ad with you:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic