[kotlin] 함수 리터럴 (with receiver)

2021. 6. 17. 10:41모바일/Android_Kotlin

리시버가 있는 함수 리터럴

fun main() {
    println(100.lambdaSum(1))
    println(100.functionSum(1))
}
//lambda(function literal) with receiver
val lambdaSum : Int.(Int) -> Int = {
    other -> plus(other)
}

//function(function literal) type with receiver
val functionSum  = fun Int.(it:Int) : Int = this + it


//101
//101

위 코드는 리시버를 가지는 함수 타입입니다.

첫번째 함수는 lambdaSum의 타입은 Int.(Int) -> Int 로 사용할 수 있는 함수타입이며, other 를 인자로 받아서 plus(other)를 리턴하는 함수입니다.

두번째 functionSum의 익명 함수 문법은 직접적으로 함수 리터럴의 receiver타입을 지정할 수 있도록 합니다.

리시버가 없는 함수 리터럴

fun Int.withoutReceiver(block (it:Int)-> Unit) = block(this)

fun main(~~){
    100.withoutReceiver{
        print(it.hashCode())
    }
}

위 코드는 인자의 람다가 리시버를 가지기 않는다 (람다 함수에. 숫자.~ 가 없음)