Kotlin은 Delegates를 통해 프로퍼티의 변경을 감지할 수 있는 매우 편리한 기능을 제공한다.
observable
Delegates.observable은 단순하게 프로퍼티가 변경됨을 감지하는 역할을 한다.
import kotlin.properties.Delegates fun main() { var watchedNumber by Delegates.observable(0) { property, oldValue, newValue -> println("`${property.name}` changed from `$oldValue` to `$newValue`") } watchedNumber = 1 watchedNumber = 2 watchedNumber = 3 }
위 코드를 실행 시키면 콘솔에 아래와 같이 출력이 된다.

vetoable
먼저 veto 라는 단어는 거부 라는 뜻이다.
Delegates.vetoable은 값이 변경 됨을 감지하여 변경을 할 것인지 말 것인지를 지정할 수 있다.
예로, 특정 프로퍼티에 대해 항상 값이 증가해야만 한다고 했을 때 아래와 같이 vetoable을 활용할 수 있다.
import kotlin.properties.Delegates fun main() { var increasingNumber by Delegates.vetoable(0) { property, oldValue, newValue -> println("`${property.name}` is tried to be changed from `$oldValue` to `$newValue`") oldValue < newValue } increasingNumber = 1 println(increasingNumber) // 1 increasingNumber = 5 println(increasingNumber) // 5 increasingNumber = 3 println(increasingNumber) // 5 }
위 코드를 실행 시키면 콘솔에 아래와 같이 출력이 된다.

'Java & Kotlin > Kotlin' 카테고리의 다른 글
[MockK] 메서드 호출 순서 검증하기 (0) | 2022.04.15 |
---|---|
[MockK] 인자 값 그대로 리턴하기 (0) | 2022.04.14 |
by lazy를 통해 지연 초기화 적용하기 (0) | 2021.11.06 |
by 키워드를 사용한 Delegation (0) | 2021.11.06 |
Kotlin Gradle Multi Module 적용하기 (0) | 2021.11.04 |
댓글