일급 객체(함수)란 다음의 3가지 조건을 충족한 객체를 의미한다.
모든 일급 객체는 변수나 데이터에 담을 수 있어야 한다.
const hello = function() {
console.log('Hello World');
}
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
Consumer<String> c = System.out::println;
c.accept("Hello World");
}
}
모든 일급 객체는 함수의 파라미터로 전달 할 수 있어야 한다.
const hello = function() {
console.log('Hello World');
}
function print(func) {
func();
}
print(hello);
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
print(System.out::println, "Hello World!");
}
public static void print(Consumer<String> c, String str) {
c.accept(str);
}
}
모든 일급 객체는 함수의 리턴값으로 사용 할 수 있어야 한다.
const hello = function() {
console.log('Hello World');
return function() {
console.log('Callback Function');
}
}
const hello2 = hello();
hello2();
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
Consumer<Integer> c = squareNumber();
c.accept(5);
}
public static Consumer<Integer> squareNumber() {
return (t) -> {
System.out.println(t * t);
};
};
}
JavaScript, Python, Ruby 등의 함수형 프로그래밍 언어의 경우에는 함수를 일급 객체로 취급하며, 상태 변경을 최소화하여 순수 함수와 고차 함수를 활용한다.
Java의 경우 8버전 이후, 함수형 인터페이스 기능을 제공하기 시작하며 함수를 일급 객체로 사용할 수 있게 되고, 람다식을 통해 함수형을 표현할 수 있게 되었다.
일급 객체의 경우 코드의 재사용성과 가독성을 크게 높일 수 있다.