This blog entry is really just a support entry for a YouTube movie I created today.
A few weeks ago, I taught a course on plain old Java… The students had LISP background and raised the questions:
Does Java have Closures?
Well, it doesn't really have direct support for closures directly, but we can achieve most of the design advantages that closures provide. In this short demo, I show how one may implement closures in Java.
Code Listing
Here is the final code listing for what I showed in the demo.
ClosureDemo.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.scispike.demo; public class ClosureDemo { public static void main(String[] args) { System.out.println("Gauss should have said : " + sum(1, 100, new EchoFunction())); System.out.println("Sum of squares from 1 to 10: " + sum(1, 10, new SquareFunction())); } public static int sum(int min, int max, Function f) { int sum = 0; for( int i = min; i <= max; i++) sum += f.apply(i); return sum; } } |
Function.java
1 2 3 4 5 6 7 |
package com.scispike.demo; public interface Function { int apply(int i); } |
SquareFunction.java
1 2 3 4 5 6 7 8 |
package com.scispike.demo; public final class SquareFunction implements Function { @Override public int apply(int i) { return i*i; } } |
EchoFunction.java
1 2 3 4 5 6 7 8 |
package com.scispike.demo; public final class EchoFunction implements Function { @Override public int apply(int i) { return i; } } |