Kotlin의 후행 람다 및 쉼표는 무엇입니까?

후행 람다와 후행 쉼표는 Kotlin을 처음 사용하는 경우 반드시 알아야 하는 두 가지 중요한 Kotlin 기능입니다!

이 기사는 원래 2022년 8월 6일 vtsen.hashnode.dev에 게시되었습니다.

Trailing lambda은 다른 프로그래밍 언어에 없는 Kotlin의 새로운 기능입니다. 적어도 나는 그것을 지원하는 다른 프로그래밍 언어를 알지 못합니다.

다음과 같은 코드를 볼 때:

var result = operateOnNumbers(a, b) { input1, input2 ->
    input1 + input2
}
println(result)


기본적으로 operateOnNumbers()에 3개의 매개변수가 있음을 의미합니다. 마지막 매개변수는 일반적으로 함수 참조 또는 lambda 에서 전달하는 함수 정의입니다.

var result = operateOnNumbers(
    input1 = a,
    input2 = b,
    operation = { input1, input2 ->
        input1 + input2
    }
)
println(result)


Somehow I am still not getting used to this trailing lambda syntax. It looks like a function implementation.

So my mind always needs to automatically map to this (the code outside the parentheses is actually the last parameter of the function) every time I see the Trailing Lambda syntax.


operateOnNumbers()의 서명 및 구현은 다음과 같습니다.

fun operateOnNumbers(
    input1: Int,
    input2: Int,
    operation: (Int, Int) -> Int): Int {

    return operation(input1, input2)
}


반면에 trailing commas은 다른 언어에서 꽤 일반적입니다.

후행 쉼표 포함

var result = operateOnNumbers(
    a, 
    b, // trailing comma here
) { input1, input2 ->
    input1 + input2
}


후행 쉼표 없이

var result = operateOnNumbers(
    a, 
    b // no trailing comma here
) { input1, input2 ->
    input1 + input2
}


이를 사용하면 diff 및 병합이 더 쉬워진다는 이점이 있습니다. 저에게는 복사 및 붙여넣기 작업이 더 쉬워집니다. 예, 복사하여 붙여넣기를 많이 합니다!

결론



이 짧은 게시물을 즐기시기 바랍니다. 나는 이것(특히 후행 Lambda)에 대해 블로그에 올리고 싶습니다. 왜냐하면 때때로 나에게 혼란스러워 보이기 때문입니다. 특히 함수 호출은 약간 복잡합니다. 괄호 안의 코드는 실제로 함수의 마지막 매개변수라는 사실을 항상 기억해야 합니다.


또한보십시오


  • Kotlin Tips and Tricks
  • 좋은 웹페이지 즐겨찾기