Created
March 22, 2020 13:02
-
-
Save latant/0939f64a56da1ba5e749c6bae6312078 to your computer and use it in GitHub Desktop.
Creating extension property with backing field in Kotlin JS.
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
//In Kotlin, we can't create 'var' extension property that requires backing field. (https://kotlinlang.org/docs/reference/extensions.html#extension-properties) | |
//However, in Kotlin JS, we can can 'create' backing fields, due to the JS Object's dynamic nature. | |
var HTMLElement.myProp: String | |
get() = this.asDynamic().myProp | |
set(value) { this.asDynamic().myProp = value } | |
//We can also create custom property delegate to remove boilerplate: | |
class DynamicProperty<T> { | |
operator fun getValue(thisRef: Any, prop: KProperty<*>) = thisRef.asDynamic()[prop.name] | |
operator fun setValue(thisRef: Any, prop: KProperty<*>, value: T) { thisRef.asDynamic()[prop.name] = value } | |
} | |
var HTMLElement.myProp: String by DynamicProperty() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment