Cannot Infer Functional Interface Type Java 8

Cannot Infer Functional Interface Type Java 8

I have a factory(Registry DP) which initializes the class:

public class GenericFactory extends AbstractFactory {

    public GenericPostProcessorFactory() {
        factory.put("Test",
                defaultSupplier(() -> new Test()));
        factory.put("TestWithArgs",
                defaultSupplier(() -> new TestWithArgs(2,4)));
    }

}

interface Validation

Test implements Validation
TestWithArgs implements Validation

And in the AbstractFactory

 protected Supplier<Validation> defaultSupplier(Class<? extends Validation> validationClass) {
        return () -> {
            try {
                return validationClass.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                throw new RuntimeException("Unable to create instance of " + validationClass, e);
            }
        };
    }

But I keep getting Cannot infer functional interface type Error. What I am doing wrong here ?

1

1 Answer

Your defaultSupplier method has an argument type of Class. You can’t pass a lambda expression where a Class is expected. But you don’t need that method defaultSupplier anyway.

Since Test and TestWithArgs are a subtypes of Validation, the lambda expressions () -> new Test() and () -> new TestWithArgs(2,4) are already assignable to Supplier<Validation> without that method:

public class GenericFactory extends AbstractFactory {
    public GenericPostProcessorFactory() {
        factory.put("Test", () -> new Test());
        factory.put("TestWithArgs", () -> new TestWithArgs(2,4));
    }    
}
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.