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?
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());
    }
}
                        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