Search code examples
javafunctionlambdainterfacesupplier

Java function interface for Supplier<T> failed to compile non-lambda


I've got this:

import java.util.function.*;
public class FluentApi {
    public Integer myfunc(){
        return Integer.valueOf(1);
    }
    public void fSupplier(Supplier<Integer> si){
        System.out.println(si.get());
    }
    public void callFunc(){
        fSupplier(myfunc); // compilation failure
    }
}

It says: myfunc cannot be resolved to a variableJava(33554515)

If I change it to a lambda function then it compiles:

    public void callFunc(){
        fSupplier(()->Integer.valueOf(1));
    }

So what is the core difference here? How can I use a non-lambda implementation here?

Thanks.


Solution

  • You will need to pass myfunc as a method reference.

    Try this:

    public void callFunc() {
        fSupplier(this::myfunc);
    }