Android/Kotlin

Higher-order-function(고차함수)

lipnus 2019. 2. 1. 14:31
반응형

Higher-order-function(고차함수)

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



함수를 인자로 받거나, 함수를 반환하는 함수

이 조건이 성립하기 위해서는 기본적으로 함수가 FirstClassCitizen이어야 함

object Main {
@JvmStatic
fun main(args: Array<String>) {
println(simpleHigherOrderFunction({ x, y -> x + y }, 10, 20)) //30

println(simpleHigherOrderFunction(sumInts, 10, 20)) //30
println(simpleHigherOrderFunction(productInts, 10, 20)) // 200
println(simpleHigherOrderFunction(twiceSumeInts, 10, 20)) // 60

println(simpleHigherOrderFunction({ a, b -> a + b }, 10, 20)) //30
println(simpleHigherOrderFunction({ a, b -> a * b }, 10, 20)) // 200
println(simpleHigherOrderFunction({ a, b -> (a + b) * 2 }, 10, 20)) // 60
}

fun simpleHigherOrderFunction(sum: (Int, Int) -> Int, a: Int, b: Int): Int = sum(a, b)
val sumInts: (Int, Int) -> Int = { a, b -> a + b }
val productInts: (Int, Int) -> Int = { a, b -> a * b }
val twiceSumeInts: (Int, Int) -> Int = { a, b -> (a + b) * 2 }
}




반응형

'Android > Kotlin' 카테고리의 다른 글

RxBus  (0) 2019.02.15
First-class citizen (1급객체)  (0) 2019.02.01
const val과 그냥 val의 차이  (0) 2019.01.22
lateinit & by lazy  (0) 2018.12.11
let, run, apply, with  (0) 2018.12.11