Skip to content

Instantly share code, notes, and snippets.

@soverby
Last active May 17, 2018 13:13
Show Gist options
  • Save soverby/b04ed8d01d1c62601181129d42e58003 to your computer and use it in GitHub Desktop.
Save soverby/b04ed8d01d1c62601181129d42e58003 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
public class FormingClosure {
Supplier<List<String>> supplier;
public static void main(String[] args) {
FormingClosure fc = new FormingClosure();
fc.go();
}
public void go() {
final List<String> someList = new ArrayList<>();
// THIS is a side effect!!!
someList.add("one");
someList.add("two");
// JUST formed a closure right here on someList. Booooooo
supplier = () -> someList;
// THIS is a side effect!!!
someList.add("three");
someList.add("four");
System.out.println(" someList:");
someList.forEach(System.out::println);
System.out.println(" --------------------- ");
System.out.println(" closure:");
supplier.get().forEach(System.out::println);
// The RIGHT way to do it:
// Everyone understand this right? It's a Function that takes a List of Strings and
// returns Supplier that supplies a List of Strings....
Function<List<String>, Supplier<List<String>>> consumer = list -> () -> list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment