Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics: Inferring types over two parameters

Tags:

java

generics

Suppose I have a simple method like this for processing two lists:

public static <B> void foo(List<B> list1, List<B> list2) {
}

And suppose I want to call it like this:

foo(ImmutableList.of(), ImmutableList.of(1));

This won't compile, because javac isn't smart enough to figure out I was trying to create two lists of Integers. Instead, I have to write:

foo(ImmutableList.<Integer>of(), ImmutableList.of(1));

How should I change the declaration of foo to allow the first version to work as well as the second one?

like image 254
Derek Thurn Avatar asked Apr 19 '12 04:04

Derek Thurn


2 Answers

I'm pretty sure Java's type inference isn't powerful enough to handle unification.

What you could do is return an intermediate object of some sort, and change the call site to be something like:

foo(list1).and(list2)

But then it would still only be able to infer from left to right, so you'd have to call it as:

foo(ImmutableList.of(1)).and(ImmutableList.of());
like image 110
Daniel Pryden Avatar answered Oct 06 '22 03:10

Daniel Pryden


The only setting in which I forsee this being an inconvenience for you is when you do this a lot. In that case you can make a

private static final ImmutableList<Integer> EMPTYINTLIST = ImmutableList.<Integer>of();

and use your EMPTYINTLIST in your calls.

like image 29
trutheality Avatar answered Oct 06 '22 03:10

trutheality