▌ TRANSMISSION · [CONCEPT]

Kotlin Basic 2


Kotlin Basic 2

Higher-Order Functions and Lambdas

고차 함수는 다른 함수를 매개변수로 받거나, 함수를 반환하는 함수이다.

람다는 이름이 없는 함수로, 값처럼 다룰 수 있다.

1. Higher-Order Functions

고차 함수는 다른 함수를 매개변수로 받거나 반환할 수 있다.

fun higherOrderFunction(param: (Type) -> ReturnType): ReturnType {
    // Function body
}

Ex.

fun operate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a, b)
}

fun main() {
    val sum = operate(4, 5, { x, y -> x + y })
    println("Sum: $sum") // Output: Sum: 9

    // Using lambda outside parentheses
    val product = operate(4, 5) { x, y -> x * y }
    println("Product: $product") // Output: Product: 20
}

Output.

Sum: 9
Product: 20

2. Lambdas Expressions

람다는 함수를 간결하게 표현하는 방법이다.

특히 고차 함수의 인수로 사용할 때 유용하다.

{ parameters -> body }

Ex.

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5)
    val doubled = numbers.map { it * 2 }
    println("Doubled: $doubled") // Output: Doubled: [2, 4, 6, 8, 10]
}

Output.

Doubled: [2, 4, 6, 8, 10]

Function Literals with Receivers (수신 객체가 있는 함수 리터럴)

Kotlin은 수신 객체가 있는 함수 리터럴을 지원한다.

  • Function Literal
    • 이름 없이 바로 만들어 쓰는 함수
  • Receiver (수신 객체)
    • 함수 안에서 this처럼 사용할 대상 객체

이를 사용하면 특히 DSL을 작성할 때 더 표현력 있고 간결한 코드를 작성할 수 있다.

Inline Functions

인라인 함수는 Kotlin에서 사용하는 성능 최적화 기법이다.

함수에 inline 키워드를 지정하면, 컴파일러가 함수 호출 부분을 실제 함수 코드로 대체한다.

이를 통해 함수 호출에 필요한 오버헤드를 줄일 수 있으며, 특히 고차 함수에서 유용하다.

inline fun functionName(parameters): ReturnType {
  // 함수 본문
}

Ex.

inline fun performOperation(
  a: Int,
  b: Int,
  operation: (Int, Int) -> Int
): Int {
  return operation(a, b)
}

fun main() {
  val sum = performOperation(3, 7) { x,y -> x + y }
  println("Sum: $sum") // Output: Sum: 10

  val product = performOperation(3, 7) { x, y -> x * y }
  println("Product: $product") // Output: Product: 21
}

Output.

Sum: 10
Product: 21

간단하게 설명하자면,

performOperation 함수는 inline으로 선언되어있다.

따라서 이 함수를 호출하는 각 위치에 performOperation 함수의 코드와 전달된 람다 코드가 직접 삽입되게 된다.

이 방식은 고차 함수 호출과 람다 객체 생성에서 발생할 수 있는 오버헤드를 줄여주며, 특히 성능이 중요한 애플리케이션에서 유용하다.


← ALL POSTS