Selena
Selena

Reputation: 2268

How to define a Function which flexibly accepts subclasses of declared type

I am trying to design a single arg function that can be applied to subclasses of the declared type:

But when I apply a function like this to a type T as below:

Function<? extends T,Boolean> function;
function.apply(T)

I get the following compilation error:

T cannot be converted to capture#2 of ? extends T

Example of the validation interface I am trying to design:

//Intent is that the function can be applied to T, or any subclass of T
public interface IBeanValidator<T> {
    public Function<? extends T, Boolean> getValidation();
}

//Class that implements this interface will accept validators for its type
public interface IValidateableBean<T> {
    public void validate(final IBeanValidator<T> validator);
}

//Interface for bean objects, which can be validated with validators designed
//for beans belong to this inheritane hierarchy
public interface IBean extends IValidateableBean<IBean> {
    public default void validate(final IBeanValidator<IBean> validator) {
        //compilation error occurs here. 
        validator.getValidation().apply(this);
    }
}

Upvotes: 0

Views: 35

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198311

Instead of a Function<? extends T, Boolean>, you actually just want a Function<T, Boolean>, which will accept subtypes of T. A Function<? extends T, Boolean> actually refers to some unknown but specific subtype of T, e.g. Function<SubT, Boolean>, which can't necessarily be applied to any T.

Upvotes: 1

Related Questions