10.4 Higher Order Functions in Java

Higher Order Function: A function that treats another function as data.

  • e.g. takes a function as input.

  • Example in Python:

def tenX(x):
   return 10*x
 
def do_twice(f, x):
   return f(f(x))
 
print(do_twice(tenX, 2))

Higher Order Functions in Java 7

Old School (Java 7 and earlier)

  • Fundamental issue: Memory boxes (variables) cannot contain pointers to functions.

    • use an interface instead:

public interface IntUnaryFunction {
	int apply(int x);
}

public class TenX implements IntUnaryFunction {
	public int apply(int x) {
   		return 10 * x;
	}
}

This code above is the same as the Python code:

def tenX(x):
    return 10*x

Now, to finish the rest of the Python code in Java:

public interface IntUnaryFunction {
	int apply(int x);
}

public class TenX implements IntUnaryFunction {
	public int apply(int x) {
   		return 10 * x;
	}
}

public class HoFDemo {
	public static int do_twice(IntUnaryFunction f, int x) {
   		return f.apply(f.apply(x));
	}
	
	public static void main(String[] args) {
   		System.out.println(do_twice(new TenX(), 2));
	}
}

This code above is equivalent to the Python code provided earlier.

Last updated