Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- fun Any.getDelegate<T>(prop: KProperty<T>): Any {
- return javaClass.getDeclaredField("${prop.name}$delegate").let {
- it.setAccessible(true)
- it.get(this)
- }
- }
- val delegate = a.getDelegate(A::b)
- val delegate = a.b.delegate
- fun Any.addObservable<T>(prop: KProperty<T>, observer: (T) -> Unit) {
- getObservableProperty(prop).observers.add(observer)
- }
- fun Any.getObservableProperty<T>(prop: KProperty<T>): ObservableProperty<T> {
- return getDelegate(prop) as ObservableProperty<T>
- }
- fun Any.getDelegate<T>(prop: KProperty<T>): Any {
- return javaClass.getDeclaredField("${prop.name}$delegate").let {
- it.setAccessible(true)
- it.get(this)
- }
- }
- class ObservableProperty<T>(
- initialValue: T,
- initialObservers: Array<(T) -> Unit> = emptyArray()) : ReadWriteProperty<Any?, T> {
- private var value = initialValue
- public val observers: MutableSet<(T) -> Unit> = initialObservers.toHashSet()
- public override fun get(thisRef: Any?, desc: PropertyMetadata): T {
- return value
- }
- public override fun set(thisRef: Any?, desc: PropertyMetadata, value: T) {
- this.value = value
- observers.forEach { it(value) }
- }
- }
- class A() {
- var b by ObservableProperty(0)
- }
- fun main(args: Array<String>) {
- val a = A()
- a.addObservable(A::b) {
- println("b is now $it")
- }
- a.b = 1
- a.b = 2
- a.b = 3
- }
- class A() {
- var foo by ObservableProperty(0)
- }
- class B() {
- var foo by ObservableProperty(0)
- }
- fun main(args: Array<String>) {
- val a = A()
- a.addObservable(B::foo) {
- println("b is now $it")
- }
- a.foo = 1
- a.foo = 2
- a.foo = 3
- }
- class Stuff(val thing: String)
- val stuff = Stuff("cool stuff")
- val thingFieldName = "${stuff.thing}$delegate"
- // value of thingFieldName is now "thing"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement