Giuseppe Pes
Giuseppe Pes

Reputation: 7912

Generic interface in java with WildCard

I am bit confused mixing Java generics interfaces and type wildcard. I am trying to implement a generic way to pass a list of options to a method where the type of the option is unknown at compile type.

I did in the following way, but I get an error at compile time.

Generic Interface :

public interface IOption<T> { 
    public T getOption();
}

This method should take in input a list of options of unknown type, so I used a wild card.

public interface IAction {
    boolean do(Iterable<IOption<?>> options);
}

The I created the following list of boolean options :

    IOption<Boolean> option =  new IOption<Boolean>(){
            @Override
            public Boolean getOption() {
                return new Boolean(doEnable);
            }           
        };
    Iterable<IProjectStateOption<Boolean>> options = 
                   Collections.singletonList(option);

but when the method do is called I get the following error :

The method do( Iterable<IOption<?>>) in the type IAction is not applicable for 
the arguments (Iterable<IOption<Boolean>>)

Upvotes: 0

Views: 5625

Answers (2)

user695992
user695992

Reputation:

You'd have to change your do method or your specific iterator since Iterable<IProjectStateOption> is not valid for Iterable<IOption>.

public interface IAction {
   boolean do(Iterable<? extends IOption> options);
}

If you want to specify the specific type of IOption then you need to to use <T> in IAction as well

public interface IAction<T>

Upvotes: 1

SLaks
SLaks

Reputation: 887415

An Iterable<Option<Boolean>> cannot be converted to an Iterable<Option<?>>, even though Option<Boolean> is convertible to Option<?>.

You want Iterable<? extends Option<?>>.

Upvotes: 1

Related Questions