I am trying to create a method in an interface with a generic return type but I fail to cast the generic to a specific type/class. But if I put the generic on the interface
The second code snippet is impossible to compile because Rain
is not T
.
When the type parameter is supplied in the class, there's no problem because the method can only return the type that was already supplied in the class declaration. In other words - T foo()
becomes Rain foo
.
However, when the type parameter is supplied to the method, then the method is obligated to return whatever type is supplied to it - so you can't return anything other than T
. In other words, the compiler can't enforce the calling method to only use foo
, but it can enforce the foo
method to return T
.