I would like to do the following:
public class ImmutableList<T> {
public <U super T> ImmutableList<U> add(U element) { ... }
}
That is, given an immutable list of T
, you can add any U
to the list to yield an immutable list of U
, with the constraint that U
must be a supertype of T
. For example
- I can add a monkey to a list of monkeys, yielding a new list of monkeys;
- I can add a human to a list of monkeys, yielding a new list of hominids (presumably the least upper bound of monkey and human);
- I can add a rock to a list of hominids, yielding a new list of
Object
(assuming rocks and hominids share no other common ancestor).
This sounds great in theory, but the lower bound on U
is not legal per the JLS. I could instead write:
public class ImmutableList<T> {
public ImmutableList<T> add(T element) { ... }
public static <U> ImmutableList<U> add(ImmutableList<? extends U> list, U element) { ... }
}
In this fashion, the compiler will correctly infer the least upper bound between the list's element type and the U
we want to add. This is legal. It also sucks. Compare:
// if 'U super T' were legal
list.add(monkey).add(human).add(rock);
// assuming 'import static ImmutableList.add'
add(add(add(list, monkey), human), rock);
I'm a big fan of functional programming, but I don't want my Java code to look like a Lisp dialect. So I have three questions:
WTF? Why is the
<U super T>
bound not legal? This question has actually been asked here before ("Why can't a Java type parameter have a lower bound?") but I think the question as phrased there is sort of muddled, and the answers there boil down to "it's not useful enough," which I don't really buy.JLS section 4.5.1 states: "Unlike ordinary type variables declared in a method signature, no type inference is required when using a wildcard. Consequently, it is permissible to declare lower bounds on a wildcard." Given the alternative
static
method signature above, the compiler is clearly able to infer the least upper bound it needs, so the argument seems broken. Can somebody argue that it is not?Most importantly: Can anybody think of a legal alternative to my method signature with the lower bound? The goal, in a nutshell, is to have calling code that looks like Java (
list.add(monkey)
) and not Lisp (add(list, monkey)
).