Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a function as an parameter to another function

I would like pass a function as an parameter to another function. For example:

void myFunction(boolean coondition, void function())
{
   if(condition) {
     function();
   }
}

It this possible in Java 8?

like image 335
Rafał Paszkowski Avatar asked Oct 16 '25 13:10

Rafał Paszkowski


2 Answers

No, you can't pass methods.

But there is a simple workaround: pass a Runnable.

void myFunction(boolean coondition, Runnable function)
{
   if(condition) {
     function.run();
   }
}

and call it like this: (using the old syntax)

myFunction(condition, new Runnable() {
    @Override
    public void run() {
        otherFunction();
    }
});

or using the new lambda syntax in Java 8 (which is mostly shorthand for the above):

myFunction(condition, () -> {otherFunction();}}
like image 163
user253751 Avatar answered Oct 18 '25 03:10

user253751


Yes, it is possible. Assuming your function does nothing, just pass a Runnable.

void myFunction(boolean condition, Runnable function)
{
   if(condition) {
     function.run();
   }
}

Assuming you have a function named function as such (void can be replaced by a return type, which will not be used):

private void function() {/*whatever*/}

you can call it like this using lambda expressions

myFunction(true, () -> function());

or like this in Java 1.1-1.7

myFunction(true, new Runnable(){public void run(){function();}});
like image 36
k_g Avatar answered Oct 18 '25 03:10

k_g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!