Functional Interfaces
A functional interface is an interface that specifies exactly on method. Functional interfaces may also have one or more default methods.
Functional ObjectsLet us begin with the
functional inteface Consumer<T>
. It
specfies exactly one method
public void accept(T t)
This takes an object of type T
and performs
some side-effect operation with it.
Why this distinction? Java has a means of creating anonymous function called lambdas.
A Python Moment
Java Lambda Syntax
Lambda | Action |
---|---|
x -> x*x |
This is a squaring function. It has a tacit return x*x;
|
(double x) -> x*x |
This squaring function insists its argument be a double. It also has a tacit return statement |
(x, y) -> x + y |
This is the addition function, with a tacit return. |
(int x) -> { y = x*x; return y; } | This is a multiline lambda. It must have an explicit return statement. It also insists its argument be an integer. |