안녕하세요! 프뚜입니다.
Scope Fuction은 객체 컨텍스트 내에서 코드 블럭을 실행할 수 있도록 해줍니다. 객체의 정보를 기본적으로 가지고 있는 코드 블럭을 만들어 사용할 수 있어 간결한 코딩을 가능하게 해줍니다.
[개발 환경]
- OS: Windows 10 64bit
- JAVA: 11
UserEntity 생성하기
class UserEntity(
private var name: String,
private var age: Int
) {
fun setName(param: String) {
this.name = param
}
fun incrementAge() {
this.age++
}
override fun toString(): String {
return "이름은 ${name}이고, 나이는 ${age}입니다."
}
}
instance로 사용 할 Class를 생성합니다. 이름 변경, 나이 추가정도의 fun이 있습니다.
let
파라미터는 it을 사용하며, 리턴 값은 lambda를 반환하는 scope function입니다.
// 2022.12.12[프뚜]: it, lambda
var user = UserEntity("프뚜", 20).let {
println("[LOG]: ${it}")
it.incrementAge()
it.setName("먹뚜")
println("[LOG]: ${it}")
}
println("[LOG]: ${user.javaClass}")
run
파라미터는 this을 사용하며, 리턴 값은 lambda를 반환하는 scope function입니다.
// 2022.12.12[프뚜]: this, lambda
var user = UserEntity("프뚜", 20).run {
println("[LOG]: $this")
incrementAge()
setName("먹뚜")
println("[LOG]: $this")
}
println("[LOG]: ${user.javaClass}")
with
파라미터는 this을 사용하며, 리턴 값은 lambda를 반환하는 scope function입니다.
// 2022.12.12[프뚜]: this, lambda
val users: List<UserEntity> = listOf(
UserEntity("프뚜", 20), UserEntity("먹뚜", 21)
)
val totalAge = with(users) {
var age: Int = 0
for (user in this) {
age += user.getAge()
}
age
}
println("[LOG]: ${totalAge}")
also
파라미터는 it을 사용하며, 리턴 값은 context를 반환하는 scope function입니다.
val user = UserEntity("프뚜", 20)
.also {
println("[LOG]: $it")
}
.also {
it.incrementAge()
}
.also {
it.setName("먹뚜")
}
.also {
println("[LOG]: $it")
}
println("[LOG]: ${user.javaClass}")
apply
파라미터는 this을 사용하며, 리턴 값은 context를 반환하는 scope function입니다.
val user = UserEntity("프뚜", 20)
.apply {
println("[LOG]: $this")
incrementAge()
setName("먹뚜")
}
.apply {
println("[LOG]: $this")
}
println("[LOG]: ${user.javaClass}")
해당 소스는 GitHub에서 받을 수 있습니다. (commit message와 게시글 제목은 동일합니다.)
https://github.com/JeongSeongSoo/tistory_kopring.git
GitHub - JeongSeongSoo/tistory_kopring: 티스토리 스프링 + 코틀린
티스토리 스프링 + 코틀린. Contribute to JeongSeongSoo/tistory_kopring development by creating an account on GitHub.
github.com
'프로그램 > KOTLIN' 카테고리의 다른 글
[Kotlin] 코틀린에서 레트로핏2(retrofit2) 설정 및 사용하기 (4) | 2022.12.26 |
---|---|
[Kotlin] 코틀린의 연산자 오버로딩 (Operator Overloading) (2) | 2022.12.15 |
[Kotlin] 코틀린의 NPE (Null Point Exception) 처리 방법 (2) | 2022.12.11 |
[Kotlin] 코틀린의 함수 (fun) (1) | 2022.12.10 |
[Kotlin] 코틀린의 반복문, 조건문, 선택문 (2) | 2022.12.09 |