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?
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.
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.
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.
I suspect it's just Java's type inference not being quite smart enough. Try
.map(p -> (Callable<SomeClass>) () -> p.funct())
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With