21

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 ?

Naman
  • 27,789
  • 26
  • 218
  • 353
user6348242
  • 211
  • 2
  • 8
  • 12
    If you're not used to functional programming, that language won't mean much to you. The idea is that "pure" functions should only read from their inputs, and only write to their return values (so there will be no side effects - the only effect of running the function is that you get the return value.) Functions that change something (modify a data structure, run IO, etc), are said to have side effects. A function without a return value had better have side effects, or else it isn't doing anything. – Edward Peters May 18 '16 at 00:37
  • @EdwardPeters Does throwing exception from the method count as side effect? – JavaLearner Apr 17 '23 at 11:40

3 Answers3

19

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.

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
8

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.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
5

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.

shmosel
  • 49,289
  • 6
  • 73
  • 138