Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for "consumer that returns value" abstraction in Java

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?

like image 748
Denis Kulagin Avatar asked Jul 30 '19 08:07

Denis Kulagin


People also ask

Where are consumers used in Java 8?

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.

What is Consumer function Java?

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) .


1 Answers

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:

  • Consumer: Takes one parameter, returns void.
  • Function: Takes one parameter, returns a value.
  • Supplier: Takes nothing, returns a value.
  • Predicate: Takes one parameter and returns a boolean.

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.

like image 168
TreffnonX Avatar answered Oct 29 '22 19:10

TreffnonX