One of main characteristics of Functional Programming is to be able to send functions as parameters to other functions.
Unfortunately in JAVA Functions are not First Class Citizens [R] which means they can't live on their own.
This also means that it is not possible to send them as parameters to other Functions and Functions can't return them.
In JAVA Functions can only leave inside Classes (which is why they are always referred as Methods).
So JAVA is using existing functionality, in the form of Functional Interface, to create workaround to achieves this.
In modern languages (like Kotlin and Swift) you simply specify which Function Data Type Variable can hold.
This is known as specifying Function Signature and includes Return Data Type and Data Types of Input Parameters.
Then when you assign Lambda Expression to such Variable Compiler can check if Lambda Expression
● has the same number of Input Parameters as specified by the Function Signature
● returns the same Data Type as specified by the Function Signature
● uses Input Parameters correctly based on their Data Types as specified by the Function Signature
Test.swift
In Java Functions can't exist on their own, they are not First Class Citizens and there is no Function Data Type.
Instead every Function needs to be defined inside the Class and then it is called a Method.
So in Java you declare Functional Interface (interface with a single Functional).
So this is how you specify Method Signature Function's Return Data Type and Data Types of Input Parameters.
And then you use this Interface when declaring a Variable that is supposed to hold a Function.
Then when you assign Lambda Expression to such Variable Compiler can check if Lambda Expression
● has the same number of Input Parameters as specified by the Functional Interface
● returns the same Data Type as specified by the Functional Interface
● uses Input Parameters correctly based on their Data Types as specified by the Functional Interface
In Java you can't specify Data Types of Lambda Input Parameters inside the Lambda Expression itself.
This is one reason you have to tell Compiler which Functional Interface is being used.
So that Compiler can check if Input Parameters are used correctly inside Lambda Expression.
Store Lambda Expression into a Variable
class Test {
public static void main(String[] args) {
//CREATE INSTANCE OF ANONYMOUS INNER CLASS THAT IMPLEMENTS FUNCTIONAL INTERFACE.
MyInterface classInstance = (name, age) -> { return(name + " is " + age + " years old"); };
}
}
//FUNCTIONAL INTERFACE MUST HAVE SINGLE ABSTRACT METHOD.
@FunctionalInterface
interface MyInterface {
public abstract String greet(String name, int age);
}