0

I have following code setup. But this is not allowed as wildcard is not allowed for Iterable.

public interface CustomInterface extends Iterable<? extends MyBaseType>{....}

CustomTypeA extends MyBaseType{....}

class CustomImpl implements CustomInterface {
 List<CustomTypeA> listA = new ArrayList();

 @Override
 public Iterator<CustomTypeA> iterator() {
    return listA.iterator();
 }
}

What actually Java tries to a achieve here by not allowing this? What modifications would get this working?

Mandroid
  • 6,200
  • 12
  • 64
  • 134
  • 2
    Does this answer your question? [Iterator of a wildcard type variable with upper bound](https://stackoverflow.com/questions/16753587/iterator-of-a-wildcard-type-variable-with-upper-bound) – Ankit Beniwal May 23 '20 at 06:08
  • 1
    That is completely different, it is not a dupe for this one. This question is asking for wildards on top level, not with local variables.@pagal – Aniket Sahrawat May 23 '20 at 06:32
  • @AniketSahrawat I know that. And if somebody looks closely, answers on that page leads to the answer of this question indirectly. – Ankit Beniwal May 23 '20 at 07:19

1 Answers1

2

When a class instance is created, it invokes the initializer of the super type. But you can't use wildcards for instance creation, hence your compiler giving an error. You must provide the exact type here.

Here's an excerpt from JLS §15.9

If TypeArguments is present immediately after new, or immediately before (, then it is a compile-time error if any of the type arguments are wildcards

One workaround would be to parameterize your class and pass that type variable to the Iterable interface implementation.

interface CustomInterface<T extends MyBaseType> extends Iterable<T>{

} 
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63