7

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:

  1. 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.

  2. 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?

  3. 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)).

Community
  • 1
  • 1
mergeconflict
  • 8,156
  • 34
  • 63
  • It's even worse than you think: even with your second api design, you won't be able to implement this. With type erasure, you're going to need to do something like pass a class object (e.g., `Class clazz`). There's no other way to write code that will generate a correct return list of the inferred type. – Ted Hopp May 30 '12 at 02:35
  • 1
    @TedHopp that's incorrect; erasure is not relevant here. The alternative Lisp-ish design is quite easily implementable, it just yields ugly client code. Try it. – mergeconflict May 30 '12 at 02:44

1 Answers1

2

You can almost do it, but Java type inference manages to suck just enough to make it not worth it.

public abstract class ImmutableList< T > {
    public interface Converter< U, V > {
        V convert( U u );
    }

    public abstract < U > ImmutableList< U > map( Converter< ? super T, ? extends U > cnv );

    public static class EmptyIL< T > extends ImmutableList< T >{
        @Override
        public < U > EmptyIL< U > map( Converter< ? super T, ? extends U > cnv ) {
            return new EmptyIL< U >();
        }
    }

    public static class NonEmptyIL< T > extends ImmutableList< T > {
        private final T tHead;
        private final ImmutableList< ? extends T > ltTail;
        public NonEmptyIL( T tHead, ImmutableList< ? extends T > ltTail ) {
            this.tHead = tHead;
            this.ltTail = ltTail;
        }
        @Override
        public < U > NonEmptyIL< U > map( Converter< ? super T, ? extends U > cnv ) {
            return new NonEmptyIL< U >( cnv.convert( tHead ), ltTail.map( cnv ) );
        }
    }

    public < U > ImmutableList< U > add( U u, final Converter< ? super T, ? extends U > cnv ) {
        return new NonEmptyIL< U >( u, map( cnv ) );
    }

    public static < V > Converter< V, V > id() {
        return new Converter< V, V >() {
            @Override public V convert( V u ) {
                return u;
            }
        };
    }

    public static < W, U extends W, V extends W > Converter< W, W > sup( U u, V v ) {
        return id();
    }

    static class Rock {}
    static class Hominid {}
    static class Human extends Hominid {}
    static class Monkey extends Hominid {}
    static class Chimpanzee extends Monkey {}

    public static void main( String[] args ) {
        Monkey monkey = new Monkey();
        Human human = new Human();
        Rock rock = new Rock();

        // id() should suffice, but doesn't
        new EmptyIL< Chimpanzee >().
            add( monkey, ImmutableList.< Monkey >id() ).
            add( human, ImmutableList.< Hominid >id() ).
            add( rock, ImmutableList.< Object >id() );

        // sup() finds the supremum of the two arguments' types and creates an identity conversion
        // but we have to remember what we last added
        new EmptyIL< Chimpanzee >().
            add( monkey, sup( monkey, monkey ) ).
            add( human, sup( monkey, human ) ). // add( human, sup( monkey, monkey ) ) also works
            add( rock, sup( human, rock ) );
    }
}

You at least get compile-time enforcement of convertibility between types, and as an added bonus you can define your own converters that go beyond just subclassing. But you can't have Java figure out that in the absence of a converter it should use the appropriate subclassing converter as a default, which would bring us to your original API.

Judge Mental
  • 5,209
  • 17
  • 22
  • Hmm, the `EmptyIL` / `NonEmptyIL` implementation is nearly identical to mine (I called them `Nil` and `Cons`). I also have an identical implementation of `map`. The thing you've added is essentially the use of an *evidence* parameter (à la the "typeclass pattern" in Scala) in `add`. Interesting approach... Not going to choose this as the "correct" answer just yet -- I want to play around with it a bit -- but it's a good candidate ;) – mergeconflict May 30 '12 at 14:46
  • I thought of it as evidence as well. Programs as proofs. – Judge Mental May 30 '12 at 15:34
  • 1
    @JudgeMental: I am happy to inform you that since Java 8 and the introduction of ["target typing"](http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html#target-typing) Java type inference sucks a little bit less and `ImmutableList l = new EmptyIL().add(monkey, id()).add(human, id());` compiles without a problem. They are getting closer and closer to proper Hindley-Milner inference for each release. :-) – Lii Apr 02 '15 at 22:32