Reputation: 133
I am relatively scaled at beginner level of knowledge in Advanced Java Generics. I wanted to define a interface something like this
public interface Transformer {
<T extends String & List<String>> T transform(String input) throws
IOException;
}
My Implementation Class A is shown as below:
public Class A implements Transformer{
....
....
@Override
public <T extends String & List<String>> T transform(String input) throws IOException {
String response = "a";
return response; // compilation error "Incompatible Types: Required T but found java.lang.String"
}
}
What I want to have : The implementation class should be able to pass a String input and return type can be String or a List. The implementation class is totally given freedom to choose either of the return types.
Question: 1. Why is the compilation error "Incompatible Types: Required T but found java.lang.String" is showing up?
Upvotes: 0
Views: 549
Reputation: 23349
I think you misunderstood intersection types.
The definition you have means: T is a String and
List<String>
, and not String OR
List<String>
, which is not possible because String is not a List<String>
and nothing can extend a String
and List<String>
because String
is final
.
Such a definition makes sense if you have an intersection between two interfaces because Java support multiple interface inheritance, or one implementation and multiple interfaces since a class can extend another implementation and implement multiple interfaces.
Because a List<String>
is capable of having zero or more Strings, you can make your method just return List<String>
.
Upvotes: 1