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?
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();}}
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();}});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With