Scope Function

이완희·2024년 7월 29일
0

코틀린 기초 타파

목록 보기
4/5

소개

코틀린 표준 라이브러리는 객체의 컨텍스트 내에서 코드를 실행할 수 있는 함수들을 제공한다. 람다 표현식과 함께 호출되면 일시적인 Scope가 형성된다. 객체의 이름없이 접근 할 수 있으며 대표적으로 let, run, with, apply, also가 있다.

FunctionObject referenceReturn valueIs extension function
letitLambda resultYes
runthisLambda resultYes
run-Lambda resultNo: called without the
context object
withthisLambda resultNo: takes the context
object as an argument
applythisContext objectYes
alsoitContext objectYes
  • let: non-nullable 객체에 대해 람다 실행, 지역 범위에서 변수를 사용하여 어떤 객체의 사용인지 파악하기 용이
  • apply: 객체 구성
  • run: 객체 구성 및 결과 계산, 표현식이 필요한 곳에서 구문 실행(non-extension)
  • also: 부가 효과
  • with: 객체에 대한 함수 호출 그룹화

정답이 있는건 아니며 상황마다 적절하게 골라 사용하면 된다. it, this가 혼동되지 않도록 조심하자.

let

  • 컨텍스트 객체는 it 사용, 람다 결과 반환
val numbers = mutableListOf("one", "two", "three", "four", "five")
val resultList = numbers.map { it.length }.filter { it > 3 }
println(resultList)

// you can rewrite so that you're not assigning the result of the list
// operations to a variable
numbers.map { it.length }.filter { it > 3 }.let{
	println(it)
}

it은 null check을 위해 많이 사용되기도 한다.

val name: String? = "Wanny"
val length = str?.let {
	println(it.length)
}

with

  • 컨텍스트 객체는 this 사용, 람다 결과 반환
  • 확장 함수가 아니므로 컨텍스트 객체가 인자로 전달 됨
//Grouping function calls on an object
val numbers = mutableListOf("one", "two", "three")
with(numbers) {
    println("'with' is called with argument $this")
    println("It contains $size elements")
}

run

  • 컨텍스트 객체는 this, 람다 결과를 반환
  • with과 비슷하지만, 확장 함수로 호출할 수 있으며 수신 객체를 this로 참조 가능
// 확장 함수로서의 run
val person = Person().run {
    name = "Kotlin"
    age = 10
    // 마지막 표현식의 결과가 반환됨
    "Name: $name, Age: $age"
}

apply

  • 컨텍스트 객체는 this, 객체 자체를 반환
val adam = Person("Wanny").apply {
    age = 15
    city = "Seoul"        
}
println(adam)

also

  • 추가 액션을 수행할 때 쓰면 좋음.
  • “and also do the following with the object”
val numbers = mutableListOf("one", "two", "three")
numbers
    .also { println("The list elements before adding new one: $it") }
    .add("four")

takeIf, takeUnless

표준 라이브러리에 포함되어 있는 함수이다. 객체는 람다 인자(it)로 접근 가능하다.

  • takeIf: 객체와 함께 조건을 만족한다면 객체를 반환, 그렇지 않다면 null 반환
  • takeUnless: 반대로 조건을 만족한다면 null 반환, 그렇지 않다면 객체를 반환
val number = Random.nextInt(100)

val evenOrNull = number.takeIf { it % 2 == 0 }
val oddOrNull = number.takeUnless { it % 2 == 0 }
println("even: $evenOrNull, odd: $oddOrNull")

출처: https://kotlinlang.org/docs/scope-functions.html

profile
인생을 재밌게, 자유롭게

0개의 댓글