kuco 23
kuco 23

Reputation: 830

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".

Upvotes: 2

Views: 811

Answers (2)

Nikolas
Nikolas

Reputation: 44486

Take a look at JavaDoc Function<T, R>. You misinterpret the usage of the function with JavaScript - this is still Java. This interface has a method Function::apply which applies this function to the given argument.

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

Upvotes: 1

Ryuzaki L
Ryuzaki L

Reputation: 40078

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);

Upvotes: 5

Related Questions