함수형 인터페이스

SeungHyunYoo·2021년 1월 24일
0

함수형 인터페이스란?

하나의 추상 메서드를 지정하는 인터페이스이다.
함수형 인터페이스는 어떻게 사용해야 할까?

여러 추상 메서드를 포함하면 안될까?

public class test {

    public interface filter{
        public int a(int x, int y);
        public int a(int x, int y, int z);
    }
    public static void main(String[] args) {
        filter answer = (x, y) -> (x + y);
        System.out.println(answer.a(1, 2));
    }
}

위와 같이 실행하면 main 함수 내부의 구문을 실행할 때 람다 표현식의 target type인 filter가 함수형 인터페이스가 아니라는 오류가 발생한다.

@FunctionalInterface?

public class test {

    @FunctionalInterface
    public interface filter{
        public int a(int x, int y);
        public int a(int x, int y, int z);
    }
    public static void main(String[] args) {
        filter answer = (x, y) -> (x + y);
        System.out.println(answer.a(1, 2));
    }
}

위와 같이 실행하면 filter 인터페이스가 함수형 인터페이스가 아니므로 @FunctionalInterface가 유효하지 않다고 오류를 발생시킨다.
(@FunctionalInterface 어노테이션은 해당 인터페이스가 함수형 인터페이스 임을 명시한다.)

올바른 사용 방법

public class test {

    @FunctionalInterface
    public interface filter{
        public int a(int x, int y);
    }
    public static void main(String[] args) {
        filter answer = (x, y) -> (x + y);
        System.out.println(answer.a(1, 2));
    }
}

추상 메서드를 하나만 지정하는 인터페이스를 정의하고 람다 표현식을 사용하면 잘 동작한다.


참고) 여러 디폴트 메소드를 포함해도 추상 메서드가 하나면 함수형 인터페이스가 될 수 있다.

public class test {

    @FunctionalInterface
    public interface filter{
        public int a(int x, int y);
        default public int a(int x, int y, int z) {
            return x + y + z;
        }
    }
    public static void main(String[] args) {
        filter answer = (x, y) -> (x + y);
        System.out.println(answer.a(1, 2));
        System.out.println(answer.a(1, 2, 3));
    }
}

결과 값이 3, 6으로 잘 동작한다.

0개의 댓글