함수적 프로그래밍 언어에서 사용되는 개념으로 익명 함수를 지칭하는 용어다. 함수적 프로그래밍을 쉽게 지원하기 위해 자바 8부터 람다식(Lambda Expression)을 지원하고 있다. 람다식은 (매개변수) -> {실행코드} 형식으로 작성된다.
함수의 이름이 없는 함수이다. 익명함수는 일급객체라(first-class object)는 특징을 가진다. 컴퓨터 프로그래밍 언어 디자인에서, 일급 객체란 다른 객체들에 일반적으로 적용 가능한 연산을 모두 지원하는 객체를 가리킨다. 보통 함수에 매개변수로 넘기기, 수정하기, 변수에 대입하기와 같은 연산을 지원할 때 일급 객체라고 한다.
reference : wikipedia(일급객체)
람다식은 함수형 인터페이스를 구현한 객체이다. 함수형 인터페이스에 선언된 추상 메소드를 구현하는 방식으로 작성된다.
interface Func {
int calc(int a, int b);
}
//추상메소드 calc() 한개만 가진 함수형 인터페이스 Func 이다.
Func f = (int a, int b) -> { return a + b; }
//OR
Func f = (a, b) -> { return a + b; }
interface Func{
int calc(int a, int b);
}
public class Example1 {
public static void main(String[] args){
Func add = (a,b) -> { return a+b;}
Func minus = (a,b) -> a-b;
System.out.println(add.calc(1,2));
System.out.println(minus.cals(5,1));
}
}
interface Func{
int calc(int a);
}
public class Example2 {
public static void main(String[] args){
Func multi = a -> a * a
System.out.println(multi.calc(3));
}
}
interface Func{
void print();
}
public class Example3 {
public static void main(String[] args){
Func f = () -> { System.out.println("Lambda Expression"); }
f.print();
f = () -> System.out.println("Another Lambda Expresssion");
f.print();
}
}
interface Func{
int calc(int a, int b);
}
public class Example4 {
public static void main(String[] args){
print(3,4, (a,b)->a+b);
}
public void print(int a, int b, Func f){
System.out.print(f.clac(a,b));
}
}
함수형 인터페이스 앞에 @FunctionalInterface 어노테이션을 사용해서, 컴파일러에게 함수형 인터페이스의 작성을 알릴 수 있다. 컴파일러에게 인터페이스가 추상 메소드가 1개만 있는 함수형 인터페이스인지 확인하도록 하여, 잘못된 인터페이스 작성을 막는 장점이 있다.
@FunctionalInterface
interface Func{ // 컴파일 오류 발생
int calc(int a);
void print();
}