Created
August 18, 2017 16:28
-
-
Save westonal/af25ff93cc20040b4437863b47309269 to your computer and use it in GitHub Desktop.
Decorator pattern for Kotlin ReadWriteProperties
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
| 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