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: package com.scispike.demo;
2:
3: public class ClosureDemo {
4:
5: public static void main(String[] args) {
6: System.out.println("Gauss should have said : " + sum(1, 100, new EchoFunction()));
7: System.out.println("Sum of squares from 1 to 10: " + sum(1, 10, new SquareFunction()));
8: }
9: public static int sum(int min, int max, Function f) {
10: int sum = 0;
11: for( int i = min; i <= max; i++)
12: sum += f.apply(i);
13: return sum;
14: }
15: }
Function.java
1: package com.scispike.demo;
2:
3: public interface Function {
4:
5: int apply(int i);
6:
7: }
SquareFunction.java
1: package com.scispike.demo;
2:
3: public final class SquareFunction implements Function {
4: @Override
5: public int apply(int i) {
6: return i*i;
7: }
8: }
EchoFunction.java
1: package com.scispike.demo;
2:
3: public final class EchoFunction implements Function {
4: @Override
5: public int apply(int i) {
6: return i;
7: }
8: }
View comments