Skip to content

Instantly share code, notes, and snippets.

@westonal
Created August 18, 2017 16:28
Show Gist options
  • Select an option

  • Save westonal/af25ff93cc20040b4437863b47309269 to your computer and use it in GitHub Desktop.

Select an option

Save westonal/af25ff93cc20040b4437863b47309269 to your computer and use it in GitHub Desktop.
Decorator pattern for Kotlin ReadWriteProperties
private fun <ThisRef, Value> ReadWriteProperty<ThisRef, Value>.decorate(): ReadWriteProperty<ThisRef, Value?> {
return DecoratorExample(this)
}
class DecoratorExample<in ThisRef, Value>(val decorated: ReadWriteProperty<ThisRef, Value>) : ReadWriteProperty<ThisRef,
Value?> {
override fun getValue(t: ThisRef, property: KProperty<*>): Value {
return decorated.getValue(t, property)
}
override fun setValue(thisRef: ThisRef, property: KProperty<*>, value: Value?) {
value?.also { decorated.setValue(thisRef, property, it) }
}
}
class SomeStringProperty : ReadWriteProperty<Any?,String> {
private var x: String = ""
override fun getValue(t: Any?, property: KProperty<*>): String {
return x
}
override fun setValue(t: Any?, property: KProperty<*>, value: String) {
x = value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment