Reputation: 383
I'm trying to learn a about method referencing in Java 8 using lambda expressions and came across something that I can't quite figure out.
I want to pass a method(1) into another method(2), such that method 2 calls method 1 and makes use of a value that method 1 returns.
I have setup a code snippet below that is as close to what I want from a pesudo perspective. In other words, it doesn't work logically, but should make it easy to understand what I want to achieve. The if (function.run() == true)
part in the handleSomething
method is completely wrong, but as stated above, should point out what I want to do.
public class Test {
public static void main(String[] args) {
int testValue = 23;
handleSomething(true, testValue, () -> checkIfZero(testValue));
handleSomething(false, testValue, () -> checkIfLargerThanZero(testValue));
}
private static boolean checkIfZero(int value) {
if (value == 0)
return true;
return false;
}
private static boolean checkIfLargerThanZero(int value) {
if (value > 0)
return true;
return false;
}
private static int handleSomething(boolean test, int value, Runnable function) {
if (test) {
System.out.println("Ignore");
return;
}
if (function.run() == true)
System.out.println("Passed");
else
System.out.println("Failed");
}
}
Again, if (function.run() == true)
does not work as run()
simply calls the method from the lambda expressions and doesn't return anything.
One way to do what I want with this setup is to pass an object into all the methods that contains the boolean value. The reference methods could set the boolean in the object and the method using the reference methods could use the boolean. This approach works, but is clumsy as I need to spread the object into the methods from the outside.
Is there a more clean approach to do this using lambda expressions (not creating interfaces etc.)?
Upvotes: 2
Views: 1279
Reputation: 21435
Using BooleanSupplier
as proposed by @Holger is a possible solution.
However I would recommend using an IntPredicate
, because this allows you to pass the testValue from handleSomething
to the predicate:
import java.util.function.IntPredicate;
public class Test {
public static void main(String[] args) {
int testValue = 23;
handleSomething(true, testValue, Test::checkIfZero);
handleSomething(false, testValue, Test::checkIfLargerThanZero);
}
private static boolean checkIfZero(int value) {
if (value == 0)
return true;
return false;
}
private static boolean checkIfLargerThanZero(int value) {
if (value > 0)
return true;
return false;
}
private static void handleSomething(boolean test, int value, IntPredicate function) {
if (test) {
System.out.println("Ignore");
return;
}
if (function.test(value))
System.out.println("Passed");
else
System.out.println("Failed");
}
}
Upvotes: 3