Created
November 22, 2017 11:02
-
-
Save Sloy/eebc96128a53a54edcffc65b6ee0953f to your computer and use it in GitHub Desktop.
A custom delegate for a property that it's deleted after reading it, so it can only be used once.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import kotlin.properties.ReadWriteProperty | |
| import kotlin.reflect.KProperty | |
| /** | |
| * With this delegate, a property will only return it's value once. Subsequent queries will return the default value. | |
| */ | |
| class GetAndForgetProperty<in R, T>(private val defaultValue: T) : ReadWriteProperty<R, T> { | |
| companion object { | |
| fun <T> getAndForget(defaultValue: T): GetAndForgetProperty<Any, T> { | |
| return GetAndForgetProperty(defaultValue) | |
| } | |
| } | |
| private var value: T? = null | |
| override fun getValue(thisRef: R, property: KProperty<*>): T { | |
| val returnValue = value ?: defaultValue | |
| value = null | |
| return returnValue | |
| } | |
| override fun setValue(thisRef: R, property: KProperty<*>, value: T) { | |
| this.value = value | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment