Search code examples
javajava-8functional-interface

How to call a function passed as argument in Java?


Well this seems kind of basic and I've searched a lot for whats wrong with the code or how to properly do this. I'm trying to simply use a function, that is passed as an argument.

import java.util.function.Function;

public class Anonymous {
    public static void main (String[] args) {
        System.out.println("Hi");
    }

    public static void useFunction (Function<Integer, Boolean> fun) {
        boolean a = fun(10);
    }
}

It tells me that "The method fun(int) is undefined for the type Anonymous".


Solution

  • Function is a functional interface with apply method, Since your function takes Integer as argument and returns Boolean, you have to call apply method by passing argument

    This is a functional interface whose functional method is apply(Object).

    boolean a = fun.apply(10);