ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Kotlin] scope function(범위 함수) - let, also, with, run, apply
    프로그래밍 language 2022. 9. 1. 23:28

    scope 함수

    • 코틀린 표준 라이브러리에는 scope 함수로 5가지가 있음 
    • scope 함수는 호출하면 임시 scope가 생기고, 이 scope 안에서는 전달된 객체에 대해 'this' 혹은 'it'을 통해 context 객체에 접근할 수 있다.
      • context 객체의 함수나 프로퍼티에 연속적으로 접근해야 할 때 유용하게 사용할 수 있음 

    • let, also, with, run, apply
      • scope 함수들 사이에 2가지 주요 차이점
        • context 객체를 참조하는 방법 (this 혹은 it)
          • run, with, apply 는 context 객체를 this로 접근
          • let, also 는 context 객체를 it으로 접근
        • return 값
          • apply, also는 context 객체를 반환
          • let, run, with는 람다식 결과를 반환

      • with, run, apply 함수를 호출할 때는 인자로 '수신객체 지정람다'를 전달함 
        • 수신 객체 지정람다: 람다식 안에서 사용할 객체를 미리 지정해 둬서 수신객체 명시 없이 프로퍼티나 메소드에 접근할 수 있는 람다
        • 코틀린 DSL에서도 수신 객체 지정 람다를 많이 사용함

     

    let

    inline fun <T, R> T.let(block: (T) -> R): R

    also

    inline fun <T> T.also(block: (T) -> Unit): T

    with

    inline fun <T, R> with(receiver: T, block: T.() -> R): R

    run

    inline fun <T, R> T.run(block: T.() -> R): R

    apply

    inline fun <T> T.apply(block: T.() -> Unit): T

     

     

     

    참고 자료

    '프로그래밍 language' 카테고리의 다른 글

    변성(Variance) 개념 정리  (0) 2022.08.31

    댓글

Designed by Tistory.