Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Consumer and side effects

Tags:

I am new to Java 8, I came across Consumer java doc and it says, "Consumer is expected to operate via side-effects." Could somebody please explain why it is said so ?

like image 286
user6348242 Avatar asked May 18 '16 00:05

user6348242


2 Answers

Consumer has method accept with the following signature

void accept(T t);

The method takes t as an input and doesn't return anything (void), and hence you can't return anything from it and replace the method call with the value it returns.

An example of a side effect would a print statement,

list.stream.foreach(System.out::println);

foreach takes a Consumer as an argument. If you think about it, the only useful thing you could do with such a method is to change the world (ie, mutate a state).

The opposite of that would a pure function, a function that doesn't mutate any state, it takes an input, and returns something, for example

Function<Integer,Integer> fn = x -> x*x;

fn here doesn't have any side effects (it doesn't mutate anything), it receives an integer and peacefully returns its square.

like image 59
Sleiman Jneidi Avatar answered Sep 29 '22 03:09

Sleiman Jneidi


According to the Consumer javadoc, a consumer must be declared with a method having the signature void accept(T). As a result, the method cannot return a value. If it did not have a side effect it would have no capability of performing any effects whatsoever.

like image 39
nanofarad Avatar answered Sep 29 '22 05:09

nanofarad