How to use generic function interface method type parameters in a lambda
generics, java, java-8, lambda
Solution
First of all, add the type arguments to the interface itself:
interface SolveFunction<In, Out> {
Out apply(In in);
}
You could implement a method:
public static <In, Out> List<Out> makeList(In in) {
return new ArrayList<Out>();
}
Which you can then use as the implementation of the lambda:
SolveFunction<String, Integer> f = Test::makeList;
System.out.println(f.apply("Hi").size());
Problem
Im trying to create a generic lambda so I dont need to redefine it for individual types. To do that I need to access the type parameters that were passed to the function. Unfortunately I didnt find any documentation on how to do that. This is an example of what I want to do but the in front of the lambda wont compile: ``` import java.util.ArrayList; public class Test { interface SolveFunction { <In, Out> Out apply(In in); } public static void main(String...args) { SolveFunction f = <In, Out> (In a) -> { ArrayList<Out> list = new ArrayList<>(); return list; }; System.out.println(f.<String, Integer>apply("Hi").size()); } } ```