Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substitute for illegal lower bounds on a generic Java method?

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

like image 712
mergeconflict Avatar asked May 30 '12 02:05

mergeconflict


People also ask

What is upper bound and lower bound in generics Java?

The Upper Bounded Wildcards section shows that an upper bounded wildcard restricts the unknown type to be a specific type or a subtype of that type and is represented using the extends keyword. In a similar way, a lower bounded wildcard restricts the unknown type to be a specific type or a super type of that type.

Do generics prevent type cast errors?

Implementing generics into your code can greatly improve its overall quality by preventing unprecedented runtime errors involving data types and typecasting.

What is a lower bound in Java?

Lower-bound is when you specify (? super Field) means argument can be any Field or superclass of Field. Try following code: Uncomment the code and check if any error comes. import java.util.ArrayList; import java.util.Collection; public class GenericsDemo { public static void validateTillStringType(Collection<?

Can a parameterized type have several bounds?

A type parameter can have multiple bounds.


1 Answers

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.

like image 138
Judge Mental Avatar answered Sep 25 '22 07:09

Judge Mental