Kotlin 범위 지정 함수(apply, run, also, let, with)

지프치프·2022년 5월 19일
0

Java/Kotlin

목록 보기
8/11
post-thumbnail

개요

Kotlin에는 범위 지정 함수(Scope Function)라는 놈이 있다.

Kotlin 공식 문서에서는 아래와 같이 설명하고 있다.

When you call such a function on an object with a lambda expression provided, it forms a temporary scope. In this scope, you can access the object without its name. Such functions are called scope functions.

쉽게 말하면 임시 스코프를 제공하는 람다식을 의미하며
이 람다식의 인자로 호출된 객체에 접근도 가능하다.

5가지의 함수가 제공되는데 하나씩 알아가보도록 하겠다.

종류


공식 문서에 나와있는 각 함수들의 명세다.

let

Executing a lambda on non-null objects
Introducing an expression as a variable in local scope

공식 문서에서는 let의 사용법을 위와 같이 권장한다.
주로 non-null 처리를 할 때 사용되며
Lamda의 마지막 줄을 반환하며 인자는 it으로 표현된다.

	val test = TestClass()
    test.testFunc(readLine())?.let {
        println(it)
    }

run

Object configuration and computing the result
Running statements where an expression is required: non-extension

run 은 인자로 this를 사용하고 Lamda의 마지막 줄을 반환한다.
그래서 객체의 대한 설정이나 일련의 처리 후 반환하는 것에 사용된다.

	val test = TestClass().run {
        age = 26
        name = "jeep"
        println(toString())
    }

run은 다른 함수들과 다르게
객체의 확장없이 단독으로도 사용이 가능하다.

    val runVal = run {
        val read = readLine()?.toInt()
        read?.plus(10)
    }
    println(runVal)

apply

Object configuration

객체를 설정할 때 주로 사용된다.
위에서 다룬 run과 비슷하지만 apply는 Lamda 전체를 반환(객체 반환)

	val test = TestClass().apply {
        age = 26
        name = "jeep"
    }
    println(test.toString())

with

Grouping function calls on an object

with는 다른 함수들과 다른 점이 있다면
확장 함수가 아니다.
인자는 this이며 반환은 람다 마지막줄을 반환한다.

with(test) {
    val list = mutableListOf<String>("Lee", "Kim", "Park")
    with(list) {
        println("list size is $size") // output list size is 3
        forEach { name ->
            print("${indexOf(name) + 1}.$name ") // output 1.Lee 2.Kim 3.Park 
        }
    }
}

사실 run으로 충분히 대체가 가능하기에 잘 쓰이진 않을 거 같다.

also

Additional effects

also는 let과 유사해보이지만 람다를 반환하는 let과 달리
람다 전체(객체 자신)을 반환한다.

    val list = mutableListOf(1, 2, 3)
    list.also {
        println("list is $it")
    }.add(4)
    println("list is $list after also")

위 코드처럼 람다식 후에 추가적인 처리를 해줄 수 있다.

개인적으로 공부했던 것을 바탕으로 작성하다보니
잘못된 정보가 있을수도 있습니다.
인지하게 되면 추후 수정하겠습니다.
피드백은 언제나 환영합니다.
읽어주셔서 감사합니다.

profile
지프처럼 거침없는 개발을 하고싶은 개발자

0개의 댓글