Closures in Minitab

Java supports anonymous functions through lambda expressions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.

import java.util.function.Supplier;

public class Closures {
    // This method returns a Supplier<Integer>, which is similar to a function
    // that takes no arguments and returns an integer. The returned supplier
    // closes over the variable i to form a closure.
    public static Supplier<Integer> intSeq() {
        final int[] i = {0};  // We use an array to simulate a mutable integer
        return () -> {
            i[0]++;
            return i[0];
        };
    }

    public static void main(String[] args) {
        // We call intSeq, assigning the result (a Supplier<Integer>)
        // to nextInt. This supplier captures its own i value, which
        // will be updated each time we call nextInt.get().
        Supplier<Integer> nextInt = intSeq();

        // See the effect of the closure by calling nextInt.get()
        // a few times.
        System.out.println(nextInt.get());
        System.out.println(nextInt.get());
        System.out.println(nextInt.get());

        // To confirm that the state is unique to that
        // particular supplier, create and test a new one.
        Supplier<Integer> newInts = intSeq();
        System.out.println(newInts.get());
    }
}

When you run this program, you’ll see the following output:

1
2
3
1

In this Java example, we use a Supplier<Integer> to represent a function that takes no arguments and returns an integer. The intSeq method returns a Supplier<Integer> that closes over the i variable, forming a closure.

We use an array with a single element to simulate a mutable integer because Java’s lambda expressions can only access final or effectively final variables from the enclosing scope.

The main method demonstrates how the closure maintains its own state across multiple invocations, and how different instances of the closure have their own independent state.

This example showcases how Java can achieve similar functionality to Go’s closures, albeit with slightly different syntax and using the Supplier interface from the java.util.function package.