Skip to content

Instantly share code, notes, and snippets.

@latant
Created March 22, 2020 13:02
Show Gist options
  • Save latant/0939f64a56da1ba5e749c6bae6312078 to your computer and use it in GitHub Desktop.
Save latant/0939f64a56da1ba5e749c6bae6312078 to your computer and use it in GitHub Desktop.
Creating extension property with backing field in Kotlin JS.
//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