Reputation: 4094
I was just wondering if there's a more efficient way to do something along the lines of this in Java.
Just going to use this dummy function as an example
static int getDivision(int number, int divider) {
if(divider == 0) { return -1; }
return (number / divider);
}
If I have a ternary operator that is checking the result of that function like the below
public static void main(String[] args) {
int result;
result = getDivision(2, 0);
System.out.println (
result == -1 ? "No" : result
);
}
I have to create a variable to store the result, otherwise I can do it like this
System.out.println (
getDivision(2, 0) == -1 ? "No" : getDivision(2, 0)
);
But I have to call the function twice which is even worse. Is it possible to use the ternary operator but include the result of a function in the conditions?
System.out.println (
getDivision(2, 0) == -1 ? "No" : /*returned result*/
);
Upvotes: 1
Views: 60
Reputation: 15706
Using Optional
, you can represent a real result as well as indicate that no result is present:
static Optional<Integer> getDivision(int number, int divider) {
return divider == 0 ? Optional.empty() : Optional.of(number / divider);
}
Usage:
Optional<Integer> result = getDivision(2, 0);
System.out.println(result.map(String::valueOf).orElse("No"));
Or if you only want to further process the result when it is present:
result.ifPresent( value -> ...);
EDIT: the value -1
is also a valid outcome of some divisions, which works fine with the Optional
as well, compared to the original approach:
Optional<Integer> result = getDivision(-5, 5);
Upvotes: 4