0

I have problem with understanding how Java wildcard works in one particular case. Let's say I have class which represents generic response

public class MyResponse<T> {

    private final int httpCode;
    private final String message;
    private final T data;
}

and resolver for that:

public class ResponseResolver {

    public void resolve(Either<AppError, MyResponse<?>> responseToResolve) {
        //some logic 
    }

    public void resolveOption(Option<MyResponse<?>> responseToResolve) {
        //some logic 
    }
}

and service where response is resolved with resolver

public class FooService {

    private final ResponseResolver responseResolver;

    public FooService(ResponseResolver responseResolver) {
        this.responseResolver = responseResolver;
    }

    public void resolveFoo() {
        Either<AppError, MyResponse<Foo>> either = Option.of(new MyResponse<>(200, "message", new Foo())).toEither(AppError.ERROR);
        responseResolver.resolve(either);
    }

    public void resolveOptionFoo() {
        MyResponse<Foo> foo = new MyResponse<>(200, "message", new Foo());
        responseResolver.resolveOption(Option.of(foo));
    }
}

I do not understand why resolveOption method which is called in resolveFooOption is a proper way but in method with Either compiler complies that required type is Either<AppError, MyResponse<?> but provided Either<AppError, MyResponse<Foo>. Can anybody explain me why second case is invalid?

ketrab321
  • 541
  • 2
  • 12
  • 22
  • Did you try `Either> either = ...`, so the type of `either` matches the parameter type of method `resolve()`? – Andreas Jul 20 '20 at 20:36
  • Yes I tried it and it works. But I am still curious about why the first version does not work. I thought that adding wildciard allows to pass any value. Especially that method with `Option>` works. – ketrab321 Jul 21 '20 at 06:22
  • Because `Either>` and `Either>` are not assignment-compatible, see [Is List a subclass of List? Why are Java generics not implicitly polymorphic?](https://stackoverflow.com/q/2745265/5221149) – Andreas Jul 21 '20 at 06:25
  • The `Option>` variant works for the same reason that `Either>` works, i.e. that `Option.of()` resolves to that type specifically, not to a type naming `Foo`. – Andreas Jul 21 '20 at 06:29

0 Answers0