user6348242
user6348242

Reputation: 221

Java 8 Consumer and side effects

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 ?

Upvotes: 22

Views: 3656

Answers (3)

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23329

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.

Upvotes: 20

shmosel
shmosel

Reputation: 50716

Most functional interfaces are meant to be just that - functional interfaces, which strictly means they accept an input, make some calculations, and return an output. They're not supposed to modify any state. Consumer is the exception because it doesn't return any values; its purpose is solely to modify some state.

Upvotes: 5

nanofarad
nanofarad

Reputation: 41281

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.

Upvotes: 8

Related Questions