코틀린 표준 라이브러리는 객체의 컨텍스트 내에서 코드를 실행할 수 있는 함수들을 제공한다. 람다 표현식과 함께 호출되면 일시적인 Scope가 형성된다. 객체의 이름없이 접근 할 수 있으며 대표적으로 let, run, with, apply, also가 있다.
| Function | Object reference | Return value | Is extension function |
|---|---|---|---|
| let | it | Lambda result | Yes |
| run | this | Lambda result | Yes |
| run | - | Lambda result | No: called without the |
| context object | |||
| with | this | Lambda result | No: takes the context |
| object as an argument | |||
| apply | this | Context object | Yes |
| also | it | Context object | Yes |
정답이 있는건 아니며 상황마다 적절하게 골라 사용하면 된다. it, this가 혼동되지 않도록 조심하자.
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)
}
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")
}
this, 람다 결과를 반환with과 비슷하지만, 확장 함수로 호출할 수 있으며 수신 객체를 this로 참조 가능// 확장 함수로서의 run
val person = Person().run {
name = "Kotlin"
age = 10
// 마지막 표현식의 결과가 반환됨
"Name: $name, Age: $age"
}
this, 객체 자체를 반환val adam = Person("Wanny").apply {
age = 15
city = "Seoul"
}
println(adam)
val numbers = mutableListOf("one", "two", "three")
numbers
.also { println("The list elements before adding new one: $it") }
.add("four")
표준 라이브러리에 포함되어 있는 함수이다. 객체는 람다 인자(it)로 접근 가능하다.
val number = Random.nextInt(100)
val evenOrNull = number.takeIf { it % 2 == 0 }
val oddOrNull = number.takeUnless { it % 2 == 0 }
println("even: $evenOrNull, odd: $oddOrNull")