1. Scope 함수
1-1) 람다식 문법 지원. 중괄호를 사용함.
instance(객체)를 함수의 parameter로 전달하여 사용하는 특징.
instance를 사용하지 않고 직접 property, method를 호출 가능하게 한다.
run, with, apply, also, let
1-2) 작업이 끝나면 instance를 반환: apply, also
작업이 끝나면 최종 값을 반환: run, let, with
1-3) this로 사용되는 scope 함수: run, apply, with
1-4) it으로 사용되는 scope 함수: let, also
1-5) 호출 대상인 this 자체를 반환하는 Scope 함수: apply, also
1-6) 마지막 실행 code(최종 값)를 반환하는 scope 함수: let, run, with
1) Apply()
참조 연산자 없이 사용 가능.
run()함수는 apply() 함수와 동일한데 작업이 끝나면 마지막 구문이 반환 값으로 사용된다는 점에 차이가 있음.
fun main(){
// apply() : 참조 연산자 없이 사용 가능. a.name, a.discount() 표현을 사용 안 함.
var a = Book("안드로이드 with kotlin", 10000).apply {
name = "[개정판]" + name
discount()
}
/* var b = Book("안드로이드 with kotlin, 10000")
b.name = "[개정판]" + b.name
b.discount()*/
var obj2 = Book("스프링 프레임워크", 35000)
var result = obj2.run{
println("상품명: ${name}, 가격: ${price}")
100
200
300
}
println("run: ${result}")
}
class Book(var name: String, var price: Int){
fun discount(){
price =- 2000
}
}
var obj3 = Book("포트폴리오", 5000000)
var result2 = obj3.let{
println("상품명: ${it.name}, 가격 ${it.price}")
200
}
println("run: ${result2}")
2) run() 함수
val listSize = listSize.size 구문을 아래처럼 간소화할 수 있음. this도 지원하지만 보통 생략.
fun main(){
var list = mutableListOf("Scope", "Function")
list.run {
val listSize = size
println("list의 길이 run = $listSize")
}
}
3) Let 함수
최종 값 사용 가능. it 지원. 생략 불가능. 다른 이름으로 변경 가능(it > target 변경 가능)
var list3 = mutableListOf("Scope", "Function")
list3.apply {
val listSize = this.size
println("list의 길이 apply = $listSize")
}
var list5 = mutableListOf("Scope", "Function")
list5.let{ target ->
val listSize = target.size
println("list의 길이 let = $listSize")
}
4) With 함수
var list4 = mutableListOf("Scope", "Function")
with(list4){
val listSize = this.size
println("list의 길이 with = $listSize")
}
5) Also 함수
instance 반환
var list6 = mutableListOf("Scope", "Function")
list6.also{
val listSize = it.size
println("list의 길이 also = $listSize")
}
6) 반환 값으로 구분하기
afterApply가 추가된 값을 가지고 있는 instance가 됨.
var list7 = mutableListOf("Scope", "Function")
val afterApply = list7.apply {
add("Apply")
count();
}
println("반환 값 apply: ${afterApply}") // toString 호출
val afterAlso = list7.also {
it.add("Also")
it.count()
}
println("반환 값 apply: ${afterAlso}")
7) 마지막 실행 code를 반환하는 함수
var list8 = mutableListOf("Scope", "Function")
val listCount = list8.let{
it.add("Run")
it.count()
}
println("반환 값 let: ${listCount}")
val lastItem = list8.run{
add("Run")
get(size-1)
}
println("반환 값 run: ${lastItem}")
val lastItemWith = with(list8){
add("Run")
get(size-1)
}
println("반환 값 with: ${lastItemWith}")
'Language > Kotlin' 카테고리의 다른 글
[Kotlin] Lateinit, Lazy (0) | 2022.02.18 |
---|---|
[Kotlin] Generic, Null (0) | 2022.02.18 |
[Kotlin] 추상 Class (0) | 2022.02.17 |
[Kotlin] 상속과 확장 (0) | 2022.02.17 |
[Kotlin] 함수 (0) | 2022.02.17 |