Search code examples
javagenericsdecorator

What's wrong with this Java decorator generic class?


I created a Java class to decorate another interface with generics. However, it always has some compiler errors. This is the tailored sample code that could reproduce the error.

public interface GenericInterface<T> {
  <U, V> GenericInterface<V> testFunc(BiFunction<? super T, ? super U, ? extends V> biFunction);
}

class GenericClass<T> implements GenericInterface<T> {

  private GenericInterface<T> delegate;
  public GenericClass(GenericInterface<T> dele) {
    this.delegate = dele;
  }

  @Override
  public <U, V> GenericInterface<V> testFunc(BiFunction<? super T, ? super U, ? extends V> biFunction) {
    GenericClass<T> impl = new GenericClass<T>(delegate);
    return impl.testFunc((t, u) -> {
      // Do something here ...
      // ...
      // Error for argument u: Required type: capture of ? super U, Provided: Object
      return biFunction.apply(t, u);
    });
  }
}

I tried a whole week and could not figure out what's wrong with it. Actually, I am new to advanced Java generics.


Solution

  • Remember, ? is like a one-use new type variable.

    Therefore, the ? super T in your argument's BiFunction generics, does not have to be the same type as the ? super T as required by the testFunc invocation.

    This is fixable:

    @Override
      public <U, V> GenericInterface<V> testFunc(BiFunction<? super T, ? super U, ? extends V> biFunction) {
        GenericClass<T> impl = new GenericClass<T>(delegate);
       BiFunction<T, U, V> b = (t, u) -> {
        // do something
        return biFunction.apply(t, u);
       };
       return impl.testFunc(b);
      }