Skip to content

Instantly share code, notes, and snippets.

@vitoksmile
Created April 26, 2022 08:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitoksmile/efe6bec246d662a1aa299972617ed16a to your computer and use it in GitHub Desktop.
Save vitoksmile/efe6bec246d662a1aa299972617ed16a to your computer and use it in GitHub Desktop.
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* getValue returns only once the exact value, in other cases [default] value will be returned
*/
private class OneShotFieldDelegate<T : Any?>(
private val default: T,
) : ReadWriteProperty<Any?, T> {
private var value: T? = null
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
val result = value ?: default
value = default
return result
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = value
}
}
fun <T> oneShow(default: T): ReadWriteProperty<Any, T> = OneShotFieldDelegate(default)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment