본문 바로가기

차근차근 코틀린

[Kotlin] High Order Function(고차함수)

✅High Order Function은 함수를 변수로 넘겨주거나 ,이를 반환하는 함수이다.

 

우선 Kotlin공식 문서의 예제를 한번 살펴보자.

 

High-order functions and lambdas | Kotlin

 

kotlinlang.org

 

fun <T, R> Collection<T>.fold(
    initial: R,
    combine: (acc: R, nextElement: T) -> R
): R {
    var accumulator: R = initial
    for (element: T in this) {
        accumulator = combine(accumulator, element)
    }
    return accumulator
}

combine parameter는 (R, T) ->  R 이라는 함수로 정의되어 있다. 즉, R과 T를 인자로 받아서 R을 반환하는 함수이다.

combine함수는 for문에서 실행되며 accumulator에 결과값이 저장된다.

 

fun main() {
    hello({a, b ->
        "$a, $b Nice to meet you!"
    })
}

fun hello(body: (String, String) -> String) {
    print(body("Hello", "peace"))
}

조금 더 쉬운 예시를 들어보면 hello라는 함수는 2개의 String 타입 인자를 받아 String값을 반환한다.

위 코드는 lambda를 이용해 다음과 같이 가독성있게 줄여 쓸 수 있다.

 

    hello { a, b ->
        "$a, $b Nice to meet you!"
    }

 

👍 지금까지는 람다식을 다른 함수의 파라미터로 전달하여 다른 함수의 매개변수에서 람다식을 호출했다.

그렇다면 일반 함수를 파라미터로 전달하여 다른 함수의 매개변수에서 호출해보자.

 

fun main() {
    calculate(100, 50, ::sum)
}

fun sum(a: Int, b: Int) = a+b

fun calculate(a:Int, b:Int, c: (Int, Int) -> Int)= c(a, b)

sum이라는 덧셈함수를 calculate함수에서 파라미터로 사용하고 있다.

하지만 sum은 lambda식이 아니기 때문에 ::을 붙여서 사용해야 한다. 또한 calculate함수의 마지막 파라미터는 sum함수의 파라미터 수와 타입이 같아야한다.