0

I have a generic method inside Box class:

public <U> Box<U> map(Transformer<T, U> transformer) {
if (this.boxContent == null) {
  return (Box<U>) EMPTY_BOX;
}

U transformed = transformer.transform(this.boxContent);
Box<U> box = new Box<U>(transformed);
return box;}

Transformer interface:

public interface Transformer<T, U> {
  public abstract U transform(T t);
}

LastDigitsOfHashCode:

class LastDigitsOfHashCode implements Transformer<Object, Integer> {

  //...
  @Override
  public Integer transform(Object t) {
    // returns Integer
  }
}

I get this error while using a test class:

method map in class Box<T> cannot be applied to given types;

  Box.of("string").map(new LastDigitsOfHashCode(2)), Box.of(3));
                        ^
  required: Transformer<String,U>

  found: LastDigitsOfHashCode

  reason: cannot infer type-variable(s) U

  (argument mismatch; LastDigitsOfHashCode cannot be converted to Transformer<String,U>)

where U,T are type-variables:

U extends Object declared in method `<U>map(Transformer<T,U>)`

T extends Object declared in class Box

U should be able to store Integer in one case and Object in another. I have tried replacing U with Object, but that didn't help. How can I solve this issue?

Charisma Kausar
  • 182
  • 3
  • 13

0 Answers0