Home > Software design >  Generic type incompatibility when invoking a method
Generic type incompatibility when invoking a method

Time:08-22

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.

CodePudding user response:

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.

  • Related