Kotlin/포스팅

코틀린 커스텀 위임 만들기

짜집퍼박사(짜박) 2024. 1. 6. 18:38

코틀린에서는 사용자 정의 프로퍼티 위임을 만들어서 특정 프로퍼티의 동작을 커스터마이징할 수 있습니다. 이를 위해서는 ReadOnlyProperty 또는 ReadWriteProperty 인터페이스를 구현해야 합니다. 각각은 읽기 전용과 읽기/쓰기 가능한 프로퍼티에 대한 인터페이스입니다.

아래에 간단한 사용자 정의 프로퍼티 위임의 예제를 제시합니다.

import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty

// ReadOnlyProperty 인터페이스를 구현한 사용자 정의 위임 클래스
class CustomReadOnlyDelegate : ReadOnlyProperty<Any?, String> {
    // getValue 메서드는 프로퍼티에 접근할 때 호출됨
    override fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return "Hello, ReadOnlyDelegate!"
    }
}

// 사용자 정의 위임을 사용하는 클래스
class Example {
    // customReadOnlyProperty에 CustomReadOnlyDelegate를 사용하여 위임
    val customReadOnlyProperty: String by CustomReadOnlyDelegate()
}

fun main() {
    val example = Example()
    println(example.customReadOnlyProperty) // 출력: Hello, ReadOnlyDelegate!
}

위의 예제에서 CustomReadOnlyDelegate 클래스는 ReadOnlyProperty 인터페이스를 구현합니다. 이 인터페이스는 getValue 메서드를 정의하고 있으며, 이 메서드는 프로퍼티에 접근할 때 호출됩니다. 이때 반환되는 값이 해당 프로퍼티의 값으로 사용됩니다.

이제 Example 클래스에서 customReadOnlyProperty 프로퍼티에 CustomReadOnlyDelegate를 사용하여 위임하고 있습니다. 이렇게 하면 customReadOnlyProperty를 읽을 때마다 CustomReadOnlyDelegate의 getValue 메서드가 호출되어 "Hello, ReadOnlyDelegate!"가 반환됩니다.

만약 쓰기 가능한 프로퍼티에 대한 사용자 정의 위임을 만들고 싶다면, ReadWriteProperty 인터페이스를 구현하면 됩니다. 사용자 정의 프로퍼티 위임을 통해 코드의 재사용성과 가독성을 높일 수 있습니다.

 

With ChatGPT

'Kotlin > 포스팅' 카테고리의 다른 글

코틀린 고차 함수와 DSL  (0) 2024.01.06
코틀린 위임 표현  (0) 2024.01.06
코틀린 표준 위임들  (0) 2024.01.06
코틀린 위임 프로퍼티  (0) 2024.01.06
코틀린 이터레이션  (0) 2024.01.05