앱 개발/Kotlin_Android
스코프 함수
lionbae
2024. 2. 21. 15:46
스코프 함수 (Scope Function, 영역 함수)는 특정 객체의 컨텍스트 안에서 속성 초기화, 활용 등 특정 동작을 실행하기 위한 목적만을 가진 함수이다. 스코프 함수 호출 시 람다 표현식을 형성하며, 그 안에서 개체 이름 없이 개체에 엑세스 할 수 있다. 스코프 함수에는 let, run, with, apply, also가 있다.
<let>
it을 사용해 프로퍼티에 접근
최종 실행 결과 반환
fun main() {
val info = Info("오소리", "tistory", 1)
val scope = info.let {
println("${it.name}라는 이름의 ${it.blog} 블로거") // 오소리라는 이름의 tistory 블로거
it.num = 10
it.num
}
println(scope) // 10
}
class Info(var name: String, var blog: String, var num: Int) {
fun plus() {
num += 1
}
}
<run>
this를 사용해 프로퍼티에 접근 (this 생략 가능)
return 값으로 객체 반환
fun main() {
val info = Info("오소리", "tistory", 1)
val scope = info.run {
println("${name}라는 이름의 ${this.blog} 블로거") // 오소리라는 이름의 tistory 블로거
this.num = 10
num
}
println(scope) // 10
}
class Info(var name: String, var blog: String, var num: Int) {
fun plus() {
num += 1
}
}
<with>
this를 사용해 프로퍼티에 접근 (생략 가능)
return 값으로 객체 반환
fun main() {
val info = Info("오소리", "tistory", 1)
val scope = with(info) {
println("${name}라는 이름의 ${this.blog} 블로거") // 오소리라는 이름의 tistory 블로거
this.num = 10
num
}
println(scope) // 10
}
class Info(var name: String, var blog: String, var num: Int) {
fun plus() {
num += 1
}
}
<apply>
this를 사용해 프로퍼티에 접근 (생략가능)
return 값으로 자기 자신을 반환 → 초기화 시 주로 사용
fun main() {
val info = Info("오소리", "tistory", 1)
val scope = info.apply {
println("${name}라는 이름의 ${this.blog} 블로거") // 오소리라는 이름의 tistory 블로거
this.num = 10
num
}
println(scope) // Info("오소리", "tistory", 10)
}
class Info(var name: String, var blog: String, var num: Int) {
fun plus() {
num += 1
}
}
<also>
it을 사용해 프로퍼티에 접근
return 값으로 자기 자신을 반환
fun main() {
val info = Info("오소리", "tistory", 1)
val scope = info.also {
println("${it.name}라는 이름의 ${it.blog} 블로거") // 오소리라는 이름의 tistory 블로거
it.num = 10
it.num
}
println(scope) // Info("오소리", "tistory", 10)
}
class Info(var name: String, var blog: String, var num: Int) {
fun plus() {
num += 1
}
}
728x90