Is there a built-in or robust third-party abstraction for consumer that returns value in Java 8+?
P.S. For deferred execution it may return Future as well.
Update. Function interface has a perfect syntactic match, but there is a consideration around semantics. Using Function in this case obviously breaks don't change external state piece of contract. How to deal with that?
The Consumer Interface is a part of the java. util. function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one argument and produces a result.
Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects. This is a functional interface whose functional method is accept(Object) .
You are probably looking for the Function<T, R>
-interface. It is generic and takes a parameter, while returning a value. it can be used for lambda expressions, for example mapping:
Integer input = 1;
Function<Integer, Integer> myMapping = a -> a * 2;
Integer myInt = myMapping.apply(input);
// myInt == 2
Take a look at the java util.function package: https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html
There is a multitude of different predefined functional interfaces. @FunctionalInterface
is the annotation marking such interfaces that definitely only have exactly one non-default method. Such interfaces can be used for lambda expressions.
here are some top candidates:
and the various derivations thereof.
All of these can be stored as "values", to be later executed. In a sense, they can become callbacks, if needed.
Edit:
Because a Function
is not expected to change the external state of it's execution, some applications for APIs seem tricky. However, if you intend to use a function in this fashion, you could define a parameter-class which is basically a wrapper for all values expected to be changed. If any of them is changed during execution, the external state is updated based on those changes. However this seems to be more of a pattern, than a simple one-class/interface langauge feature. I used parameter classes before, even before lambda expressions, and it works well, if the right javadocs are properly described.
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