Kotlin
Kotlin Scope Function (let, with, apply, run, also)
어쩌다 개발자 주인장
2023. 11. 28. 10:49
Scope Function
자기 자신의 객체를 전달해서 효율적인 처리를 한다.
| Scope에서 접근방식 this | Scope에서 접근방식 it | |
| 블록 수행 결과를 반환 | run, with | let |
| 객체 자신을 반환 | apply | also |
let function
// let
var strNum = "10"
var result = strNum?.let {
// 중괄호 안에서는 it으로 활용함
Integer.parseInt(it)
}
run function & with function
+ run은 with와 달리 null 체크 가능
+ with는 반드시 null이 아닐 때만 사용 + this생략해서 사용 가능
// run
var student = Student("참새", 10)
student?.run {
displayInfo()
}
// with
var alphabets = "abcd"
with(alphabets) {
// var result = this.subSequence(0,2)
var result = subSequence(0,2)
println(result)
}
also function & apply function
// also
var student = Student("참새", 10)
var result = student?.also {
it.age = 50
}
result?.displayInfo()
student.displayInfo()
// apply
var student = Student("참새", 10)
var result = student?.apply {
student.age = 50
}
result?.displayInfo()
student.displayInfo()