Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating generic lambdas in Java

In java, you can add Type parameters to static methods, to create methods that handle generics. Can you do the same with lambdas?

In my code I have

final private static <K,V> Supplier<Map<K, List<V>> supplier=HashMap::new;

I'm trying to do type parameters like it's a function, but it won't let me.

And if I do:

    final private static Supplier<Map<?, List<?>>> supplier=HashMap::new;

It doesn't accept the argument where I try to use it. What can I do?

like image 661
Joe Avatar asked Aug 23 '15 14:08

Joe


1 Answers

One workaround for this may be to wrap the method reference into a method, so that target type deduction resolves the type at the call site:

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

public class GenericLambda
{
    // Syntactically invalid
    //final private static <K,V> Supplier<Map<K, List<V>> supplier=HashMap::new;

    final private static Supplier<Map<?, List<?>>> supplier=HashMap::new;

    // A workaround
    private static <K,V> Supplier<Map<K, List<V>>> supplier()
    {
        return HashMap::new;
    }


    public static void main(String[] args)
    {
        // Does not work
        //useSupplier(supplier);

        // Works
        useSupplier(supplier());
    }

    private static <K, V> void useSupplier(Supplier<Map<K, List<V>>> s)
    {
        System.out.println(s.get());
    }
}
like image 54
Marco13 Avatar answered Sep 18 '22 03:09

Marco13