개발/Java

Java 기초부터 다시 - interface Function<T, R>

삽쟁이 2024. 1. 29. 15:37
반응형
@FunctionalInterface
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);
    ......

자바8 이후 부터 제공되는 기본 함수형 인터페이스 Funtion<T, R>은 T 타입의 인자를 받아 R타입의 인자를 반환하는 apply라는 추상 메소드를 제공한다.

 

사용 예제 (기본)

// Integer 타입의 수를 인자로 받아 +10 후, Integer 타입 반환
Function<Integer, Integer> plus10_v1 = new Function<Integer, Integer>() {
    @Override
    public Integer apply(Integer integer) {
        return integer + 10;
    }
};
//람다 표현1
Function<Integer, Integer> plus10_v2 = (i) -> i + 10;
//람다 표현2
Function<Integer, Integer> plus10_v3 = (i) -> {
	i = i + 10;
    return i;
};
plus10_v1.apply(10); // result Integer 20
plus10_v2.apply(10); // result Integer 20
plus10_v3.apply(10); // result Integer 20

이렇게 IN, OUT 인자 타입만 잘 맞춰 주면 자유롭게 사용이 가능하다.

반응형

사용 예제 (기타 Default 메소드)

Default Method란 자바8 이후 추가된 기능으로 기본 인터페이스에 추상 메소드가 추가 될 경우, 이를 상속받는 모든 Class에 해당 메소드를 구현해야 하는 이슈가 있었지만, Default 메소드는 메소드의 구현체를 제공 함으로써 기존의 추상메소드가 구현된 Class가 깨지지 않고 사용 가능하게 해주는 기능이다.

 

Default 메소드각 몇개가 있던 추상 메소드가 1개일 경우, FuntionalInterface로 간주 된다.

// 위에 Funtion 기능을 상속받아 구현한 클래스
public class Plus10 implements Function<Integer, Integer> {
    @Override
    public Integer apply(Integer integer) {
        return integer + 10;
    }

    @Override
    public <V> Function<V, Integer> compose(Function<? super V, ? extends Integer> before) {
        return Function.super.compose(before);
    }

    @Override
    public <V> Function<Integer, V> andThen(Function<? super Integer, ? extends V> after) {
        return Function.super.andThen(after);
    }
}

Funtion<T, R>에서 제공되는 Default 메소드는 compose , andThen 2가지의 Default 메소드를 제공한다.

 

compose : 인자로 받은 Funtion 의 Apply를 먼저 적용 후, 본체의 Apply 적용.

andThen: 본체의 Apply를 적용 후, 인자로 받은 Funtion의 Apply 적용.

 

이렇게만 보면... 뭔말인지 모르겠으니 예제 코드로 확인해 보자.

Plus10 plus10 = new Plus10();
// 받은 인자의 x2를 하는 Funtion
Function<Integer, Integer> multiply = integer -> integer * 2;

System.out.println(plus10.apply(10)); // result : 20
System.out.println(plus10.compose(multiply).apply(20)); // result (20 * 2) + 10 = 50
System.out.println(plus10.andThen(multiply).apply(2)); // result (2 + 10) * 2 = 24

 

첫번째 출력 값 : 인자로 받은 10에 +10을 한 값을 반환.

두번째 출력 값 : 인자로 받은 20을 Compose의 인자인 multiply의 apply(x2)를 먼저 적용 후, 본체의 apply(+10)을 적용.

세번째 출력 값 : 인자로 받은 2를 본체의 apply(+10) 을 먼저 적용 후, addThen의 인자인 multiply의 apply(x2)를 적용.

반응형