1일1배움/Java

[23/07/20] 메서드 참조 ::

kim chan jin 2023. 7. 20. 15:35
package functionalInterface;

import java.util.function.Function;

public class Test {
    public static void main(String[] args) {

        // 함수형 인터페이스 생략 후
        Function<String, Integer> f = (String s) -> Integer.parseInt(s);

        // 함수형 인터페이스 생략 전
        Function<String, Integer> f2 = new Function<String, Integer>() {
            @Override
            public Integer apply(String s) {
                return Integer.parseInt(s);
            }
        };

        // 커스텀 함수형 인터페이스
        CustomFunction<String, Integer> f3 = new CustomFunction<String, Integer>() {
            @Override
            public Integer apply(String s) {
                return Integer.parseInt(s);
            }
        };

        // 람다식이 메서드 1개만 호출한다면 메서드 참조 가능
        Function<String, Integer> f_ref = Integer::parseInt;

        // 람다식이 메서드 2개 이상을 호출한다면 메서드 참조 불가
        Function<Integer, Integer> doubleAndPrint = n -> {
            int doubled = n * 2; // 메서드 1
            System.out.println("Doubled: " + doubled); // 메서드 2
            return doubled;
        };

        int result = doubleAndPrint.apply(5); // 출력 결과: "Doubled: 10"
        System.out.println("Result: " + result); // 출력 결과: "Result: 10"

        System.out.println(f.apply("77"));
        System.out.println(f.getClass());

        System.out.println(f2.apply("66"));
        System.out.println(f2.getClass());

        System.out.println(f3.apply("55"));
        System.out.println(f3.getClass());

        System.out.println(f_ref.apply("44"));
        System.out.println(f_ref.getClass());
    }
}

@FunctionalInterface
interface CustomFunction<T, U> {
    U apply(T t);
}

많은 함수형 인터페이스(Supplier, Consumer, Predicate, UnaryOperator, BinaryOperator 등)가 있지만

위 예시에서는 Function 함수형 인터페이스만 예시로 들었다

 

람다식은 메서드를 주고 받는 것처럼 보이겠지만

// 함수형 인터페이스 생략 후
Function<String, Integer> f = (String s) -> Integer.parseInt(s);

사실은 함수형 인터페이스 선언과 동시에 익명객체를 생성한 엄연한 객체이다.

// 함수형 인터페이스 생략 전
Function<String, Integer> f2 = new Function<String, Integer>() {
    ...오버라이딩...
};

// 커스텀 함수형 인터페이스
CustomFunction<String, Integer> f3 = new CustomFunction<String, Integer>() {
    ...오버라이딩...
};

 

 

람다식 덕분에 긴 코드를 간결하게 쓸 수 있지만, 더 간결하게 표현할 수 있다!

// 람다식이 메서드 1개만 호출한다면 메서드 참조 가능
Function<String, Integer> f_ref = Integer::parseInt;

 

단, 람다식이 하나의 메서드만 호출하는 경우에 "메서드 참조"라는 방법으로 람다식을 간략하게 할 수 있다.

// 람다식이 메서드 2개 이상을 호출한다면 메서드 참조 불가
Function<Integer, Integer> doubleAndPrint = n -> {
    int doubled = n * 2; // 메서드 1
    System.out.println("Doubled: " + doubled); // 메서드 2
    return doubled;
};

int result = doubleAndPrint.apply(5); // 출력 결과: "Doubled: 10"
System.out.println("Result: " + result); // 출력 결과: "Result: 10"