1

I have an interface that is named Record and another interface OrganizationRecord that extends the first one as follows:

public interface OrganizationRecord extends Record { /// }

I have a function foo(Map<String, Map<String, List<? extends Record>>> records)

And I call it with a parameter of type Map<String, Map<String, List<OrganizationRecord>>> as shown below:

Map<String, Map<String, List<OrganizationRecord>>> records = getRecords(); // A function I can't control which returns the map as the signature shows
foo(records);

I get the following message:

java: incompatible types: java.util.Map<java.lang.String,java.util.Map<java.lang.String,java.util.List<OrganizationRecord>>> cannot be converted to java.util.Map<java.lang.String,java.util.Map<java.lang.String,java.util.List<? extends Record>>>

What am I missing here? If OrganizationRecord is defined as extends Record - why wouldn't this invocation work?

I also tried changing the foo signature to accept Map<String, ? extends Map<String, List<? extends Record>>> because I thought the issue was happening as I may change the maps that are the values to the main keys, but this still doesn't work.

Avi
  • 21,182
  • 26
  • 82
  • 121
  • 1
    I think the problem is one of the maps. Map> is not the same as Map>. The idea that generics are not covariant applies to the outer Map here. C.f.: https://stackoverflow.com/questions/71530768/why-cant-i-assign-a-listliststring-to-a-listlist-variable – markspace Aug 21 '22 at 16:10
  • @markspace - Thank you for your comment. So I tried to change the map in the function signature, as mentioned in the last paragraph but still it raises an incompatibility error issue – Avi Aug 21 '22 at 16:19
  • I had to use `foo(Map>> records)` - that's three `? extends`. If I omit any of them, I get a compiler error. – Rob Spoor Aug 21 '22 at 16:22
  • @RobSpoor - You're right! Thank you! If you want to right it as an answer, feel free. I'll upvote and accept. Thanks! – Avi Aug 21 '22 at 16:29

1 Answers1

1

I had to use foo(Map<String, ? extends Map<String, ? extends List<? extends Record>>> records) - that's three ? extends. If I omit any of them, I get a compiler error.

Avi
  • 21,182
  • 26
  • 82
  • 121
Rob Spoor
  • 6,186
  • 1
  • 19
  • 20