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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
clink
  • 213
  • 3
  • 11
  • 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()`. – Boris the Spider Apr 22 '18 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 '18 at 13:33
  • Add a code example of what you are trying to do. "_Aside from the example you gave_" - what are you envisaging? – Boris the Spider Apr 22 '18 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 '18 at 13:36
  • @clink look at the possible duplicate. I think this (plus some research) will answer your question. – Turing85 Apr 22 '18 at 13:37

1 Answers1

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));
    }
}
SeverityOne
  • 2,476
  • 12
  • 25
  • Java 8 lambdas are syntactic sugar for anonymous classes - nothing more. – Boris the Spider Apr 22 '18 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. – SeverityOne Apr 22 '18 at 14:00