Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use generic function interface method type parameters in a lambda

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());
    }
}
like image 718
user1703761 Avatar asked Mar 21 '23 14:03

user1703761


1 Answers

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());
like image 183
Jesper Avatar answered Apr 06 '23 09:04

Jesper