Hanbit the Developer

Kotlin Documentation | Lamdas 본문

Mobile/Kotlin

Kotlin Documentation | Lamdas

hanbikan 2023. 5. 23. 17:16

Kotlin Documentation 시리즈에 대해

Category: Concepts - Functions

문서 링크: https://kotlinlang.org/docs/lambdas.html


Higher-order functions

fun postRequest(req: Request, onSuccess: (String) -> Unit) {
	// ... Call network with req
	onSuccess(result)
}

Function types

  • (A, B) -> C
  • A.(B) → C
  • suspend () → Unit
  • (x: Int, y: Int) → Point: 문서화를 위해 x, y라는 네이밍을 한 것임
  • ((Int, Int) → Int)?
  • (Int) → ((Int) → Unit)

Instantiating a function type

  • lambda function: { a, b → a + b }
  • anonymous function: fun(a: Int, b: Int): Int { return a + b }
  • a callable reference to an existing function: ::isOdd, String::toInt, foo::toString
  • a custom class implementing a function type as an interface
  • class IntTransformer: (Int) -> Int { override operator fun invoke(x: Int): Int = TODO() } val intFunction: (Int) -> Int = IntTransformer()
  • (A, B) -> C can be passed as A.(B) -> C

Invoking a function type instance

val intPlus: Int.(Int) -> Int = Int::plus

intPlus.invoke(1, 2)
intPlus(1, 2)
1.intPlus(2) // extension-like call

Lambda expressions and anonymous functions

Passing trailing lambdas

함수의 마지막 파라미터가 고차함수일 경우 람다 표현식을 사용할 수 있다:

fun <T, R> Collection<T>.fold(
    initial: R,
    combine: (acc: R, nextElement: T) -> R
): R { /* ... */ }

val product = items.fold(1) { acc, e -> acc * e }
run { println("...") } // If the lambda is the only argument in the call

it: implicit name of a single parameter

ints.filter { it > 0 }

Returning a value from a lambda expressions

ints.filter {
    val shouldFilter = it > 0
    shouldFilter
}

ints.filter {
    val shouldFilter = it > 0
    return@filter shouldFilter
}

Underscore for unused variables

map.forEach { (_, value) -> println("$value!") }

Anonymous functions

lambda는 반환값을 명시하지 않고 자동으로 추론하게 된다. 하지만 반환값을 명시하고 싶은 경우 익명 함수를 사용할 수 있다.

fun(x: Int, y: Int): Int {
    return x + y
}

*lambda에서의 return은 람다 바깥 스코프에서의 반환이 가능하지만, anonymous function에서의 return은 일반적인 함수처럼 해당 함수의 반환을 하게 된다.