3

The interface method definition is:

Optional<? extends ABC<String, String>> getContextInfo();

The following method implementation compiles successfully in the implementation:

Optional<XYZ<String, String>> getContextInfo(){
...
}

Here XYZ is a subclass of ABC.

However, if the interface method uses a Map within Optional as follows:

Optional<Map<String,? extends ABC<String, String>>> getContextWithMap();

the following method implementation fails on compilation with the error: Attempting to use incompatible return type

Optional<Map<String, XYZ<String, String>>> getContextWithMap(){
...
}

I use java 8 and haven't tested this on higher versions. Why does compilation flag an incompatible return type error in this case? How can this be fixed?

Savior
  • 2,727
  • 2
  • 16
  • 41
seriousgeek
  • 819
  • 2
  • 12
  • 24
  • "How can this be fixed?" Just change the method signature so that the two matches? I guess you can't do that (otherwise you wouldn't have asked)... What restrictions do you have? What can/can't you change? – Sweeper Apr 23 '20 at 15:30
  • Or https://stackoverflow.com/questions/13229979/java-nested-generic-type-mismatch – Savior Apr 23 '20 at 15:32
  • I could fix it by adding the generic return type in my implementation but I don't like to have generics within my implementation. More interested in why it is unsafe, so that I can think about an alternate approach. – seriousgeek Apr 23 '20 at 15:39
  • This boils down to asking why you can't assign a `Optional>>` to a reference of type `Optional>>`. – Andy Turner Apr 23 '20 at 15:47
  • You still haven't said whether the link given by Savior answers your question. If it does, I'll close this as a dupe. If not, please explain why not. – Sweeper Apr 23 '20 at 15:48
  • I was going over the answers suggested above. Have closed this as a duplicate. – seriousgeek Apr 23 '20 at 15:49

0 Answers0