Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java "target type of lambda conversion must be an interface"

I'm trying to use lambdas and streams in java but I'm quite new to it. I got this error in IntelliJ "target type of lambda conversion must be an interface" when I try to make a lambda expression

List<Callable<SomeClass>> callList = prgll.stream()                                           .map(p->(()->{return p.funct();} )) <--- Here I get error                                           .collect(Collectors.toList()); 

Am I doing something wrong?

like image 480
Mocktheduck Avatar asked Dec 23 '15 00:12

Mocktheduck


People also ask

What is the target type of a lambda expression?

The parentheses for specifying the parameter can be omitted for a single-parameter lambda expression. The target type of the lambda expression—the functional interface ActionListener —is inferred from the context, which is a method invocation.

What is target type java?

The Target-Type of an expression is the data type that the Java Compiler expects depending on where the expression appears. Java 8 supports inference using Target-Type in a method context.

What are lambda expressions in Java?

A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.


2 Answers

I suspect it's just Java's type inference not being quite smart enough. Try

 .map(p -> (Callable<SomeClass>) () -> p.funct()) 
like image 69
Louis Wasserman Avatar answered Oct 26 '22 18:10

Louis Wasserman


Stream#map() is a typed method, so you can explicitly specify the type:

 .<Callable<SomeClass>>map(p -> () -> p.funct()) 

or neater, use a method reference:

 .<Callable<SomeClass>>map(p -> p::funct) 
like image 38
Bohemian Avatar answered Oct 26 '22 17:10

Bohemian