Closures Considerations - UnquietCode/Closures-for-Java GitHub Wiki

These examples should help clarify some of the 'gotchas' that you might run into while using Closure classes.

	public void changingTest() {
		// Keep in mind that unless you pass in a copy, your object can be mutated.

		Map<Integer, Character> map = new HashMap<Integer, Character>();
		map.put(0, 'A');
		map.put(1, 'B');

		Closure<Integer> encoder = new AbstractClosure<Integer>(map) {

			public Integer run(Object...args) {
				char x = ((Map<Integer, Character>)a1()).get(0);
				char y = ((Map<Integer, Character>)a1()).get(1);

				return (x + y) % (Integer) args[0];
			}
		};

		int AB = encoder.run(5);    // original
		map.put(1, 'C');            // mutate
		int AC = encoder.run(5);    // new value

		out("AB code: " + AB);
		out("AC code: " + AC);
		out();
		
		// However, the initial values can be stored in the intializer section of the closure.

		char array[] = {'D', 'E'};
		Closure<Integer> encoder2 = new AbstractClosure<Integer>(array) {
			char x = ((char[])a1())[0];
			char y = ((char[])a1())[1];

			public Integer run(Object...args) {
				return (x + y) % (Integer) args[0];
			}
		};

		int DE = encoder2.run(5);   // original
		array[1] = 'F';             // mutate
		int DF = encoder2.run(5);   // doesn't affect the closure

		out("DE code: " + DE);
		out("DF code: " + DF + " (not really!)");
	}
⚠️ **GitHub.com Fallback** ⚠️