Java Reference
In-Depth Information
public
public interface
interface
MyFunctionalInterface
MyFunctionalInterface
{
int
int
compute
(
int
int
x
);
}
This could be used to process an array of integers as:
public
public class
class
ProcessIntsFunctional
ProcessIntsFunctional
{
static
static
int
int
[]
integers
= {
0
,
1
,
2
,
3
,
4
,
5
};
/** Function to be called with an int and a Function;
* just apply the function to the int and return the result
*/
static
static
int
int
doTheMath
(
int
int
n
,
Function
<
Integer
,
Integer
>
func
) {
return
return
func
.
apply
(
n
);
}
public
public static
static
void
void
main
(
String
[]
args
) {
int
int
total
=
0
;
for
for
(
int
int
i
:
integers
) {
// Call doTheMath with 'i' and a Lambda for n^2 +1
total
+=
doTheMath
(
i
,
k
->
k
*
k
+
1
);
}
System
.
out
.
println
(
total
);
}
}
If
compute
were a nonfunctional interface—having multiple abstract methods—you would
not be able to use it in this fashion.
To ensure that a given interface is and remains functional, there is a
@FunctionalInterface
annotation, whose use is analogous to
@Override
(both annotations are in
java.lang
). It is
always optional, and is always used to ensure that a given interface conforms to the contract
of being a functional interface. Our preceding interface could sport the annotation like so:
@FunctionalInterface
public
public interface
interface
MyFunctionalInterface
MyFunctionalInterface
{
int
int
compute
(
int
int
x
);
}
If somebody later working on the code were to add an additional method: