0

I'm new to Java and I'm confused about actual parameters in Java. Since it's just parameters, I assume that literals, constants,variables, expressions can be actual parameters during function calling.

But I'm confused about a function call. Is it possible to have a function call being an actual parameter in Java?

5
  • 2
    No. It is not possible to pass functions as first class citizens. However, the result of a function can be; for example foo(bar()) - bar() will be called and the result of that function will be passed as an argument to foo(). Apr 22, 2018 at 13:31
  • @BoristheSpider so in other words, in any circumstances, a function call can never be part of an actual parameter? Aside from the example you gave.
    – clink
    Apr 22, 2018 at 13:33
  • Add a code example of what you are trying to do. "Aside from the example you gave" - what are you envisaging? Apr 22, 2018 at 13:35
  • @BoristheSpider I'm not coding at the moment, just trying to grasp on what can be parameters in java.
    – clink
    Apr 22, 2018 at 13:36
  • @clink look at the possible duplicate. I think this (plus some research) will answer your question.
    – Turing85
    Apr 22, 2018 at 13:37

1 Answer 1

0

If your question is "are functions first-class citizens in Java, as they are in C" then the question is "no, not really".

But with Java 8's lambdas, you can get pretty close:

import java.util.function.IntFunction;

public class Main {

    public static void main(String[] args) {

        final IntFunction square = x -> x * x;
        printFunctionResult(square, 2);
    }

    public static void printFunctionResult(final IntFunction function, final int value) {
        System.out.println(function.apply(value));
    }
}
2
  • Java 8 lambdas are syntactic sugar for anonymous classes - nothing more. Apr 22, 2018 at 13:52
  • Not quite, there are some profound differences between the two. And I think that my answer points out very clearly that a function (or method, to use the Java parlance) is not a first-class citizens, like objects and primitives are. Apr 22, 2018 at 14:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.