0

Say I have a utils function:

public static <T extends Number> double myFunc(List<T> a1, List<T> a2) {...}

Next, I have a class:

class Config<T extends Number>{
    public List<T> buckets;
    public List<T> groups;
}

Finally, I want to write a function, like so:

double execute(Config<? extends Number> config){
    //Some stuff
    myFunc(config.buckets, config.groups)
}

However, this gives me a compile time error: "The method myFunc(List< T>, List< T>) is not applicable for the arguments (List< capture#1-of ? extends Number>, List< capture#2-of ? extends Number>)".

I have a guess as to why the compiler doesn't like this.. Basically, myFunc requires both argument lists to have the same type parameter T extends Number, but I'm supplying ? extends Number for both, so it has no way to ensure that both will be the same type parameter? (I've encountered this error, so I'm guessing that's responsible here as well..) But I'm using the same Config<? extends Number> config object's buckets and groups fields, which if you see the class definition, have the same type T as defined in the class level type parameter. So aren't they guaranteed to have the same type parameter?

Is the issue somewhere else?

Thanks in advance for making it all the way to the end.

mave_rick
  • 59
  • 8
  • It is the issue you described. Try changing the method signature to `public double execute(Config config)` . – Andrew S Jul 17 '18 at 15:25
  • Here is my friend, bounded wildcards. https://stackoverflow.com/questions/3009745/what-does-the-question-mark-in-java-generics-type-parameter-mean – kidnan1991 Jul 17 '18 at 15:34
  • Yeah, reify the type. – Johannes Kuhn Jul 17 '18 at 19:20
  • @AndrewS why would that work? Whatever type the config has (represented by the ?), it will be the same for its buckets and groups.. so why should using T make a difference – mave_rick Jul 18 '18 at 04:51
  • My basic point is this, in the scope of the `execute` function, the `config` object is defined with a particular type parameter, thus its `buckets` and `groups` fields have that same parameter, and I'm passing those to the `myFunc` function. So they're guaranteed to be the same type right? Am I wrong in saying that? If not, then why does the compiler not see that? – mave_rick Jul 18 '18 at 09:07
  • No, they're not guaranteed to be the same type. [This](https://stackoverflow.com/questions/2776975/how-can-i-add-to-list-extends-number-data-structures) is a good explanation. – Andrew S Jul 18 '18 at 12:54
  • Na, I understand List extends Number> is read only. But this is a separate issue. Whatever, I'll keep reading – mave_rick Jul 18 '18 at 13:02

0 Answers0