Reputation: 37
I just have a small doubt on lambdas.I'm getting the below error with the following code.If i'm calling a method which returns boolean or other type, I don't see this issue.How can i solve this problem?
Error:
Exception in thread "main" java.lang.Error: Unresolved compilation problems: The method forEach(Consumer) in the type Iterable is not applicable for the arguments (( bean) -> {}) The target type of this expression must be a functional interface
at com.wipro.MethodReference.main(MethodReference.java:18)
package com.sample;
import com.student.MockClass;
import java.util.ArrayList;
import java.util.List;
public class MethodReference {
public static void main(String[] args) {
MockClass obj = new MockClass("JSP", 2);
MockClass obj1 = new MockClass("Java", 8);
List<MockClass> listofBeans = new ArrayList<MockClass>();
listofBeans.add(obj);
listofBeans.add(obj1);
listofBeans.forEach(bean -> MethodReference::call);
}
public static void call(){
System.out.println("Hii!!!");
}
}
Upvotes: 2
Views: 5600
Reputation: 30686
JLS described Method Reference Expression:
A method reference expression is compatible in an assignment context, invocation context, or casting context with a target type T if T is a functional interface type (§9.8) and the expression is congruent with the function type of the ground target type derived from T.
So you must assign/cast it to a function interface.
listofBeans.forEach(bean-> ((Runnable)MethodReference::call).run());
is equivalent to :
listofBeans.forEach(bean-> call());
Upvotes: 3
Reputation: 6463
The purpose of functional interfaces (in this case a Consumer
) is to pass data through the stream. Your method call()
makes not much sense since it accepts no parameter and returns nothing. You can do it but not with a method reference.
Try this instead:
listofBeans.forEach(MethodReference::call);
public static void call(MockClass bean){...}
or
listofBeans.forEach(bean -> call());
Upvotes: 2