Issue
What is a reason behind class generic declaration and method generic argument E extends MyError are not considered to have the same bound?
class Err<T, E extends MyError> {
private E error;
public <newT, newE extends MyError> Err<newT, newE> doSomething() {
return new Err<newT, newE>(error);
}
}
IntelliJ says Required type:newE, Provided:E
Isn't both E and newE have the same bounds so they should be interchangeable? Meaning newE return type extends MyError and E also extends MyError, so why can't I use error value if both E and newE bounds are the same (e.g. extends MyError)?
How can I keep this X extends Y dynamic behavior so that everything that satisfies extends MyError can be used to instantiate Err class?
Solution
The compiler (or IntelliJ) says that because the type parameters E and newE are completely separate type parameters.
Note that the field error is of type E, and inside your method you are treating it as if it is of type newE - you get an error because those are not the same types.
Why did you declare the type parameters newT and newE on the method? You could just use the T and E that were declared on the class:
class Err<T, E extends MyError> {
private E error;
Err(E error) {
this.error = error;
}
public Err<T, E> doSomething() {
return new Err<>(error);
}
}
(Note: class Err in your example is also missing a constructor).
Answered By - Jesper
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.