0

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?

1
  • the return value of the transform method needs to extend a String (which it cant since String is final) and implement the List<String> interface. I highly doubt thats something you wanted... you should rephrase your question so that your target is clear... Commented May 23, 2016 at 19:37

1 Answer 1

1

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>.

Sign up to request clarification or add additional context in comments.

2 Comments

Appreciate for your response. I understood your answer.I was actually looking to see if Java Generics has an option to support like T extends String or List<String>. It might be dumb but looking around the docs and tutorials. How to work around to define a interface which accepts String input and returns a response of type String or Collection ?
@saripallivskp As I said, a Collection is capable of having zero or more values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.