스코프 함수란?
✔ 코드를 축약해서 표현할 수 있도록 도와주는 키워드처럼 쓰이는 함수
run
- 호출 대상 this (생략 가능)
- 마지막 코드 반환
// Example 1
var list = mutableListOf("Scope", "Function")
list.run {
val listSize = size
println("리스트의 길이 run = ${listSize}")
}
// Example 2
val lastItem = list.run {
add("Run")
get(size - 1)
}
println("반환값 run = ${lastItem}")
// 리스트의 길이 run = 2
// 반환값 run = Run
let
- 호출 대상 it (생략 불가능, 변환 가능)
- 마지막 코드 반환
// Example 1
var list = mutableListOf("Scope", "Function")
list.let { // it -> 이 생략된 형태
val listSize = it.size
println("리스트의 길이 let = ${listSize}")
}
// Example 2
val lastCount = list.let {
it.add("Run")
it.count()
}
println("반환값 let = ${lastCount}")
// 리스트의 길이 let = 2
// 반환값 let = 3
apply
- 호출 대상 this (생략 가능)
- 자기 자신을 반환
// Example 1
var list = mutableListOf("Scope", "Function")
list.apply {
val listSize = size
println("리스트의 길이 apply = ${listSize}")
}
// Example 2
val afterApply = list.apply {
add("Apply")
count()
}
println("반환값 apply = ${afterApply}")
// 리스트의 길이 apply = 2
// 반환값 apply = [Scope, Function, Apply]
also
- 호출 대상 it (생략 불가능, 변환 가능)
- 자기 자신을 반환
// Example 1
var list = mutableListOf("Scope", "Function")
list.also {
val listSize = it.size
println("리스트의 길이 also = ${listSize}")
}
// Example 2
val afterAlso = list.also {
it.add("Also")
it.count()
}
println("변환값 also = ${afterAlso}")
// 리스트의 길이 also = 2
// 반환값 also = [Scope, Function, Also]
with
- 호출 대상 this (생략 가능)
- 마지막 코드 반환
- 주로 binding 중복을 피하기 위해 사용
// Example 1
var list = mutableListOf("Scope", "Function")
with (list) {
val listSize = size
println("리스트의 길이 with = ${listSize}")
}
// Example 2
val lastItemWith = with(list) {
add("With")
get(size - 1)
}
println("반환값 with = ${lastItemWith}")
// 리스트의 길이 with = 2
// 반환값 with = With
'Kotlin' 카테고리의 다른 글
[Android] [Kotlin] 지연 초기화 (0) | 2021.08.30 |
---|---|
[Android] [Kotlin] Null Safety (0) | 2021.08.30 |
[Android] [Kotlin] 설계 도구 (0) | 2021.08.30 |
[Android] [Kotlin] 클래스 (0) | 2021.08.30 |
[Android] [Kotlin] 함수 (0) | 2021.08.30 |