VER: Java8 ⬆
개발을 하다보면 동일한 코든데, 내부에서 호출하는 메서드만 달라지는 경우가 종종 있다.
이런 경우 메서드도 파라미터로 넘기고 싶다는 강렬한 욕망이 생기곤 한다...
자바8은 그러라고 함수형 인터페이스를 제공해준다.
https://bcp0109.tistory.com/313
https://inpa.tistory.com/entry/%E2%98%95-%ED%95%A8%EC%88%98%ED%98%95-%EC%9D%B8%ED%84%B0%ED%8E%98%EC%9D%B4%EC%8A%A4-API
그렇지만 실제로 메서드를 파라미터로 넘기는건 아니고 메서드 참조를 넘기는 것이라고 하네요?
아무튼 Mapper 메서드 넘길 때 잘 썼음 ^.^
마땅한 예제가 생각나는게 없어서 계산기로 해봤다...
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.function.BiFunction;
class Operator {
public static Integer plus(Integer a, Integer b){
return a + b;
}
public static Integer minus(Integer a, Integer b){
return a - b;
}
public static Integer multiply(Integer a, Integer b){
return a * b;
}
public static Double divide(Integer a, Integer b){
return a / (double) b;
}
}
class Main {
public static <T,S> S calculator(T a, T b, BiFunction<T, T, S> operator){
return operator.apply(a,b);
}
public static void main(String[] args) {
System.out.println(calculator(10,3,Operator::plus));
System.out.println(calculator(10,3,Operator::minus));
System.out.println(calculator(10,3,Operator::multiply));
System.out.println(calculator(10,3,Operator::divide));
}
}
