본문 바로가기

프로그래밍 언어/Kotlin

[Kotlin] Scope Function

kotlin Scope Function에는 apply, also, with, run, let 총 5가지의 Function이 있다.

 

자기 자신의 객체를 반환하는 함수

1. apply

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

apply는 객체의 프로퍼티(속성)을 정의할 때 사용한다. 

val product: Product = Product().apply { // this
    id = 1
    name = "컴퓨터"
    price = 1000000
    category = Category.ELECTRONICS
}

data class Product(
    var id: Int = 0,
    var name: String = "",
    var price: Int = 0,
    var category: Category? = null
)

 

2. also

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

수신 객체를 사용하지만, 수신 객체의 속성이 바뀌지 않을 때 주로 사용한다.

val product: Product = Product().also{ // it
    isVaild(it)
    addCart(it)
}

 

블록의 마지막 데이터 반환

3. let

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

non-null check를 통해 수신 객체가 null이 아닌 경우에만 동작하기 때문에 수신 객체가 null이 아닌 경우에만 실행을 원할 때 주로 사용한다. 

수신 객체를 파라미터 it으로 받아 사용하며, 블록의 마지막 데이터를 반환하는 것이 특징이다.

var product: Product? = null

product?.let {...}

4. run

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

특정 계산 후 결과를 반환하고자 할 때 사용하며, 어떤 객체를 생성하기 위한 코드들을 하나로 묶어 가독성을 높이는 역할을 한다.

run은 let과 같이 non-null check를 하고 실행되며, 파라미터가 아닌 Receiver(this) 형태로 수신객체가 전달되는 특징을 갖고 있다.

val saleProduct: SaleProduct = Product().run{
    val discount = 20
    val discountPrice = getDiscountPrice(price, discount)
    
    SaleProduct(
        id = id, 
        name = name,
        price = discountPrice,
        category = category
    )
}

5. with

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

with는 수신 객체가 null이면 사용할 수 없고, 주로 객체 단위로 무언가 작업을 할 때 객체 변수의 중복 사용을 줄이는데 유용하다.

with(binding){ // this
    titleTv.text = "Scope Function"
    contentTv.text = "With"
}

'프로그래밍 언어 > Kotlin' 카테고리의 다른 글

Coroutine Flow  (0) 2025.05.30
Channel  (0) 2025.05.29
runCatching 예외 처리  (0) 2025.03.08
[Kotlin] 정렬  (0) 2024.06.11
[Kotlin] 배열과 리스트 복사  (0) 2024.03.06