일급 객체(first-class object)

  • 일급 객체의 정의
    • 다른 객체에 일반적으로 적용 가능한 연산을 모두 지원하는 객체
  • 일급 객체의 조건
    • 모든 일급 객체는 변수나 데이터에 담을 수 있어야함
    • 모든 일급 객체는 함수의 파라미터로 전달할 수 있어야함
    • 모든 일급 객체는 함수의 리턴값으로 사용할 수 있어야함
// first-class object ex)
public class Main {
    // 2.메서드 매개변수로 람다식 전달
     public static void sqrt(Consumer<Integer> c, int t) {
        c.accept(t);
    }

    // 3.람다식 자체를 리턴
    public static Consumer<Integer> sqrt() {
        return (t) -> {
            System.out.println(Math.sqrt(t));
        };
    }

    public static void main(String[] args) {
        // 1.람다식을 함수형 인터페이스 타입 변수에 대입
        Consumer<Integer> sqrt = (t) -> {
            System.out.println(Math.sqrt(t));
        };
        // 1
        sqrt.accept(25); 

        // 2
        sqrt((t) -> System.out.println(Math.sqrt(t)), 25);

        // 3
        Consumer<Integer> c = sqrt();
        c.accept(25);
    }
}

Leave a comment