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

Time:07-07

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.

CodePudding user response:

You will need to pass myfunc as a method reference.

Try this:

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

CodePudding user response:

Your method have one parameter of type Supplier<Integer> so you have three choices to pass as argument to this method (the idea is to pass an instance of a class who implements the functional interface Supplier):

  • A lambda expression

    public void callFunc() {
        fSupplier(()->Integer.valueOf(1));
    }
    
  • A method reference

    public void callFunc() {
         fSupplier(this::myfunc);
     }
    
  • An anonymous inner class

     public void callFunc(){
         fSupplier(new Supplier<Integer>() {
    
             @Override
             public Integer get() {
                 return Integer.valueOf(1);
             }
         }); 
     }
    
  • Related