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