Function Objects JAMIE ZHOU AUSTIN NICCUM ALEC TIEFENTHAL

Function Objects JAMIE ZHOU, AUSTIN NICCUM, ALEC TIEFENTHAL

What are function objects? Basically objects that exist to wrap functions that you can call later ◦ Comparable, Runnable ◦ Function objects are usually represented in java by interfaces with single methods that are implemented in classes that require or are functions.

Why use a function object? Callback functions Allows different implementations with same signature for different use cases Carries its own state Enables more dynamic behavior of functions

Function Objects specific to Java Lack of first class functions Interface substitute Anonymous classes

Python Example class Accumulator(object): def __init__(self, n): self. n = n def __call__(self, x): self. n += x return self. n

Continued >>> a = Accumulator(4) >>> a(5) 9 >>> a(2) 11 >>> b = Accumulator(42) >>> b(7) 49

Comparators Passed to sort() Allow sorting by custom parameters Also can control order of data structures and order for collections that don’t have natural ordering

Inner class implementation List<String> list = Arrays. as. List("10", "1", "20", "11", "21", "12"); Comparator<String> num. String. Comparator = new Comparator<String>() { public int compare(String str 1, String str 2) { return Integer. value. Of(str 1). compare. To(Integer. value. Of(str 2)); } }; Collections. sort(list, num. String. Comparator);

Independent class implementation public class String. Length. Comparator implements Comparator<String> { @Override public int compare(String o 1, String o 2) { return o 1. length() - o 2. length(); } }

Another type of comparator public class Reverse. Alphabetical. Comparator implements Comparator<String> { @Override public int compare(String o 1, String o 2) { return -1 * o 1. compare. To(o 2); } }

Sources http: //docs. oracle. com/javase/7/docs/api/java/util/Comparator. html http: //en. wikipedia. org/wiki/Function_object http: //stackoverflow. com/a/7369600 http: //www. cs. duke. edu/csl/docs/jgl/user/Functions. html http: //download. java. net/jdk 8/docs/api/java/util/function/package-summary. html http: //progtutorials. tripod. com/cpp 1. htm#_Toc 50820124
- Slides: 11