Java

[Java] 람다식 - 메서드 참조

MbyM 2020. 7. 13. 18:30

참고 :

 - EFECTIVE JAVA 3/E

 - https://palpit.tistory.com/675

 

람다보다는 메서드 참조를 사용하라

: 메서드 참조를 사용하는 편이 더 짧고 간결하다. 즉, 람다로 작성할 코드를 새로운 메서드에 담은 다음, 람다 대신 그 메서드 참조를 사용하는 식

 

메서드 참조는 람다의 간단명료한 대안이 될 수 있다. 메서드 참조 쪽이 짧고 명확하다면 메서드 참조를 쓰자.

-> 람다식에서 불필요한 매개 변수를 제거 그리고 참조를 통한 어떤 동작을 하는지 유추

 

//두개의 (Integer) 인자를 받는 람다식
(left, right) -> Math.max(left, right);


//메소드 참조
Math::max;

//AS-IS
IntBinaryOperator operator = (left,right) -> Math.max(left,right);

//TO-BE
IntBinaryOperator operator = Math::max;

 

- > IntBinaryOperator 인터페이스는 두 개의 int 매개값을 받아 int 값을 리턴하므로 동일한 인자와 동일한 값을 리턴하는 Math.max 메소드를 참조하여 대입 할 수 있다.

 

정적 메소드 참조 ->  "클래스 :: 메소드"

 -  Class::staticMethod  (Math::max)

 

인스턴스 메소드 참조 -> "참조 변수 :: 메소드"

-  a::Method

 

생성자 참조 -> "클래스 :: new"

- Class :: new

 

public class A {
    public int operator(int a,int b){
        if(a == b) return 1;
        else return -1;
    }

    public static int 정적메소드_operator(int a,int b){
        if(a == b) return 1;
        else return -1;
    }
}



@Test
public void test_람다식_메소드_참조(){
    A a = new A();

    IntBinaryOperator operator_with_인스턴스_메서드_참조 = a::operator;
    IntBinaryOperator operator_with_정적_메소드_참조 = A::정적메소드_operator;

    assertThat(operator_with_인스턴스_메서드_참조.applyAsInt(1,1)).isEqualTo(a.operator(1,1));
    assertThat(operator_with_인스턴스_메서드_참조.applyAsInt(1,2)).isEqualTo(a.operator(1,2));

    assertThat(operator_with_정적_메소드_참조.applyAsInt(1,1)).isEqualTo(A.정적메소드_operator(1,1));
    assertThat(operator_with_정적_메소드_참조.applyAsInt(1,2)).isEqualTo(A.정적메소드_operator(1,2));

}