Backend/Java8
#2 Function Interface
RadderNepa
2022. 9. 14. 01:00
● 도입
- 함수가 1급 시민이 되기 위해서는 함수를 object 형태로 나타내야한다.
- 이를 가능하게 해주는 것이 java의 Function Interface이다.
- 핵심 : 함수를 object 형태로 나타내보자
프로그래밍에서 1급 시민의 조건
1. 함수/메서드의 매개변수(parameter)로서 전달할 수 있는가
2. 함수/메서드의 반환값(return)이 될 수 있는가
3. 변수에 담을 수 있는가
● Function Interface
- 위의 interface 중에서 Function이라는 Interface에 대해 알아보자
// Function interface는 아래와 같이 생겼다.
@FunctionalInterface
public interface Function<T, R> {
R apply(T t); // 추상 메소드
// T : apply method의 input type
// R : apply method의 return type
}
- Function interface는 T type의 input을 받아 R type의 값을 return 하는 함수를 interface 형태로 구현한 것이다.
● 실습
- Integer를 받아 (+10)을 해서 return을 해주는 함수를 object의 형태로 나타내보자
[Adder class]
package com.fastcampus.functionalprogramming.chapter3.util;
import java.util.function.Function;
public class Adder implements Function<Integer, Integer>{
@Override
public Integer apply(Integer x) { // function interface를 구현할 함수
return x + 10;
}
}
[Chapter3Section1 class]
package com.fastcampus.functionalprogramming.chapter3;
import java.util.function.Function;
import com.fastcampus.functionalprogramming.chapter3.util.Adder;
public class Chapter3Section1 {
public static void main(String[] args) {
// Function interface를 이용해
// Integer를 받아 (+10)을 해서 return을 해주는 '함수를 object의 형태로 구현'했다.
Function<Integer, Integer> myAdder = new Adder();
int result = myAdder.apply(5);
System.out.println("result : " + result);
}
}