Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

how does lambda map to functional interface in different locations ?  RSS feed

 
Linwood Hayes
Ranch Hand
Posts: 46
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I define a functional interface in my class like



Then inside this class, when I do (int a, int b) -> a +b;  it knows it should match "MathOperation" interface since that's the only one that matches.   However, if the above interface code is NOT in the same class as (int a, int b) -> a +b;
how does it know which one should be ?  For example , if I define some interfaces like


Then in my code

 
Jeanne Boyarsky
author & internet detective
Sheriff
Posts: 37242
519
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Linwood,
Great question. You don't just define a lambda in isolation. Instead you assign it to a variable or pass it as it to a method as a parameter. This means the compiler has context to figure out which interface you are talking about.

In other words, the compiler uses the context to figure out what it should be.
 
Linwood Hayes
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jeanne.  So I can do SecondClass.MathOperation op = (a,b)->....
or
ThridClass.MathOperation op2 = (a,b)->....

right ?
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!