javaarraysfunctorfunction-object

Cannot find symbol of written method java.util.function


I have code like

public class Functionz {
    public static boolean test() {
        return true;
    }

    public static void main(String[] args) {
        Function[] funcs = new Function[] {test}; // and others
        for (Function func : funcs) {
            func();
        }
    }
}

and my error is: cannot find symbol: test in the line with the function array declaration.

Hope this isn't a stupid question, very new to java, not new to object oriented languages like python and C++.


Solution

  • A Function in Java does takes one parameter as input and one as output.
    You might declare parameter's type this way : Function<Integer, String> is a function that transforms an Integer into a String
    Your method test() does not take any input value and outputs a boolean so it's a Supplier.

    import java.util.function.Supplier;
    
    public class Main {
        public static boolean test() {
            System.out.println("lorem ipsum");
            return true;
        }
    
        public static void main(String[] args) {
            Supplier[] funcs = new Supplier[] {Main::test}; // and others
            for (Supplier func : funcs) {
                func.get();
            }
        }
    }
    

    Your code would compile if test requires one (and only one parameter) like

    import java.util.function.Function;
    
    public class Main {
        public static boolean test(String str) {
            System.out.println(str);
            return true;
        }
    
        public static void main(String[] args) {
            Function[] funcs = new Function[] {(Object anyObject) -> test(anyObject.toString())}; // and others
            for (Function func : funcs) {
                func.apply("lorem ipsum");
            }
        }
    }
    

    Here's the list of those types
    Please note that Function doesn't type its parameters in construction because you can't create arrays with generic type in Java (you might for specific usecases) => Use a List will help you here