Home Ask Login Register

Developers Planet

Your answer is one click away!

Srinivas Kothuri February 2016

Functional interface as argument of the same

While exercising lambdas in Java 8, I came across the below functional interface.

interface MyFunctional {
  void invokeSame(MyFunctional myFunc);

Could you tell me how can I provide lambda expression for this Functional interface?


Alex February 2016

The same way as any other one argument and void return type lambda:

MyFunctional f = myFunc -> {};

Majeed Siddiqui February 2016

Concept: Type checking in java 8 lambdas is done based on target (the function to which it is being passed as an argument).

Explanation: Generally a function is defined by 3 attributes:

  1. Function Name.
  2. Type and order of arguments passed.
  3. Return type of function.

But while passing an lambda Java only checks for last two. So for above Functional Interface we need lambda with [first] argument type MyFunctional and return type void.

void doSomething(MyFunctional x) {
  x.invokeSame(...An object/lambda of type MyFunctional...)

To call this function
doSomething(varName -> { ...someCode... })

Post Status

Asked in February 2016
Viewed 1,290 times
Voted 12
Answered 2 times


Leave an answer

Quote of the day: live life