코틀린에서 제공하는 표준 위임은 주로 kotlin.properties 패키지에 포함되어 있습니다. 여러 표준 위임 중에서 대표적인 몇 가지를 살펴보겠습니다.
1. lazy
lazy는 프로퍼티를 처음 사용할 때까지 초기화를 지연시키는 데 사용됩니다. 다음은 lazy를 사용한 간단한 예제입니다.
val lazyValue: String by lazy {
println("Computed!")
"Hello Lazy"
}
fun main() {
println(lazyValue) // 첫 번째 호출 시에만 "Computed!" 출력, 이후 호출은 초기화된 값을 반환
println(lazyValue) // 두 번째 호출부터는 "Computed!" 출력 없이 초기화된 값을 반환
}
2. observable
observable은 프로퍼티의 값이 변경될 때 호출되는 리스너를 등록할 수 있는 표준 위임입니다.
import kotlin.properties.Delegates
class User {
var name: String by Delegates.observable("Default") { property, oldValue, newValue ->
println("$property has changed from $oldValue to $newValue")
}
}
fun main() {
val user = User()
user.name = "Alice"
user.name = "Bob"
}
3. vetoable
vetoable은 프로퍼티의 값 변경을 허용하거나 거부할 수 있는 기능을 제공합니다.
import kotlin.properties.Delegates
class User {
var age: Int by Delegates.vetoable(20) { property, oldValue, newValue ->
println("$property is changing from $oldValue to $newValue")
newValue >= 0 // 변경을 거부하려면 false를 반환
}
}
fun main() {
val user = User()
user.age = 25 // 유효한 변경, 출력: "age is changing from 20 to 25"
println(user.age) // 출력: 25
user.age = -5 // 유효하지 않은 변경, 출력: "age is changing from 25 to -5"
println(user.age) // 출력: 25 (변경이 거부되어 원래 값이 유지됨)
}
4. map
map은 맵을 프로퍼티처럼 사용할 수 있도록 해주는 위임입니다.
import kotlin.properties.Delegates
class User {
var userAttributes: Map<String, Any?> by Delegates.mapOf(
"name" to "John",
"age" to 30,
"isSubscribed" to true
)
}
fun main() {
val user = User()
println(user.userAttributes["name"]) // 출력: John
println(user.userAttributes["age"]) // 출력: 30
println(user.userAttributes["isSubscribed"]) // 출력: true
}
5. NotNull
NotNull은 프로퍼티에 null 값을 허용하지 않도록 강제하는 위임입니다.
import kotlin.properties.Delegates
class User {
var name: String by Delegates.notNull()
}
fun main() {
val user = User()
// println(user.name) // 초기화되지 않았기 때문에 IllegalStateException이 발생
user.name = "Alice"
println(user.name) // 출력: Alice
}
이외에도 다양한 표준 위임이 존재하며, 사용자 정의 위임을 만들어 사용할 수도 있습니다. 이러한 위임을 통해 프로퍼티의 동작을 커스터마이징하고 중복 코드를 줄일 수 있습니다.
With ChatGPT
'Kotlin > 포스팅' 카테고리의 다른 글
코틀린 위임 표현 (0) | 2024.01.06 |
---|---|
코틀린 커스텀 위임 만들기 (0) | 2024.01.06 |
코틀린 위임 프로퍼티 (0) | 2024.01.06 |
코틀린 이터레이션 (0) | 2024.01.05 |
코틀린 구조 분해 (0) | 2024.01.04 |