| 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 | Object reference | Yes |
also | it | Object reference | Yes |
inline fun <T, R> T.let(block: (T) -> R): R
it로 참조하며, 블록의 결과값을 반환val str: String? = "Hello, World!"
val length = str?.let {
println(it) // "Hello, World!" 출력
it.length // 블록의 결과: 13
}
inline fun <R> run(block: () -> R): R
inline fun <T, R> T.run(block: T.() -> R): R
this로 참조하며, 블록의 결과값을 반환val result = "Hello".run {
println(this) // "Hello"를 출력
length // 블록의 결과: 5
}
inline fun <T, R> with(receiver: T, block: T.() -> R): R
run과 유사하지만, 확장 함수가 아니며 객체를 직접 인자로 받음this로 참조하며, 블록의 결과값을 반환val person = Person("John", 25)
val info = with(person) {
name = "kopring"
age = "24"
"Name: $name, Age: $age"
}
// info = "Name: kopring, Age: 24"
inline fun <T> T.apply(block: T.() -> Unit): T
this로 참조하며, 블록 실행 후 객체 자체를 반환val person = Person().apply {
name = "John"
age = 25
}
// person은 설정된 객체 자체이다.
inline fun <T> T.also(block: (T) -> Unit): T
it로 참조하며, 블록 실행 후 객체 자체를 반환val str = "Hello".also {
println(it) // "Hello"를 출력
}
참고 자료
https://hyeon9mak.github.io/using-kotlin-scope-function-correctly/