Functional Programming in Java, Second Edition: Chapter 12, p.207 - The key is really mutability

As traditional , the “impure” code of page 207 in the form of a pretend test.

(Doesn’t “impure” refer to performing uncontrolled side effects, like printing to Stdout in the middle of a function though? Here, the lambda of the of the map is really a function of two parameters, one of which is pulled from the context, but it being mutable ruins everything. The key is presence of mutability.

Suppose we have a lambda expression that depends on a field in a class.

That’s okay!

Suppose we have a lambda expression that depends on a mutable (non final) member in a surrounding context.

That’s not okay!

package chapter12;

import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.stream.Collectors;

public class Impure {

    private int factor = 2; // it's mutable, which is bad (it's not even volatile either)

    @Test
    void impureFunction() {
        final var numbers = List.of(1, 2, 3);
        final var stream = numbers.stream()
                .map(number -> number * factor);
        factor = 0;
        System.out.println(stream.collect(Collectors.toList()));
    }

}

The output here happens to be [0, 0, 0].