본문 바로가기

IT/kotlin언어

[코틀린] Higher order function 정리

안녕하세요 남갯입니다


오늘은 코틀린의 higher order function에 대해 포스팅해보려고합니다.




- higher order function 이란?


higher order function은 간단하게 두개를 만족하는 함수를 일컫습니다.


1. 함수에 파라미터로 전달하는 함수

2. 함수를 반환(리턴)하는 함수



higher order function이 되기위해선 일급객체(first class citizen)가 되어야합니다.



- 일급객체(firstclass citiezen) 이란?


일급객체란 아래의 조건을 만족하는것을 말합니다.


1. 변수나 데이터 할당 할 수 있어야한다.


val test1: () -> Unit = { println("firstCitizen") }
// firstCitizen


2. 객체의 인자로 넘길 수 있어야한다.

val test2: (Int) -> Unit = { println("firstCitizen : ${it}") }
fun mytest(f: () -> Unit) {
f.invoke()
}
mytest { Main.test2(1000) }
// firstCitizen : 1000


3. 객체의 리턴값으로 리턴 할 수 있어야한다.


fun mtest(): () -> Unit {
return { println("firstCitizen") }
}


- 출처 : https://medium.com/@lazysoul/functional-programming-%EC%97%90%EC%84%9C-1%EA%B8%89-%EA%B0%9D%EC%B2%B4%EB%9E%80-ba1aeb048059




- higher order function 사용



함수의 인자로 아래와같이 

fun calculator (result : (Int,Int) -> Int) : Int{
return result(1,2)
}


calculator를 만들었습니다. 


여기에다가 넣을 sum함수를 만들어 보도록 하겠습니다.


fun sum(a : Int , b : Int) = a + b
//or
fun sum(a : Int , b : Int) = {a + b}

1. 이런 함수를 생성하고  메소드 레퍼런스를 이용해 아래와같이 표현하던지

calculator(::sum)


2. 전달해줄 인자를 생성해서 넘겨주셔도 됩니다.

val s: (Int, Int) -> Int = { a, b -> a + b }
calculator(s)


3. 바로 생성해서 넘겨주셔도 됩니다.,

calculator({ a, b -> a + b })



출처 : https://medium.com/@lazysoul/high-order-function-%EA%B3%A0%EC%B0%A8%ED%95%A8%EC%88%98-22b147d0c4a5

https://thdev.tech/kotlin/2017/10/02/Kotlin-Higher-Order-Function/