Skip to content

Instantly share code, notes, and snippets.

@HarryTylenol
Last active December 8, 2019 04:08
Show Gist options
  • Save HarryTylenol/aa7945c5faaa6abc6e9b6a7ce59dc1d7 to your computer and use it in GitHub Desktop.
Save HarryTylenol/aa7945c5faaa6abc6e9b6a7ce59dc1d7 to your computer and use it in GitHub Desktop.
Auto HashMappable Object with Kotlin (Thanks to Property Delegation!)
class User : HashMappable() {
var name: String by HashMappableProperty("")
var age: Int? by HashMappableProperty(null)
}
fun main() {
val harry = User()
harry.name = "Harry"
harry.age = 21
print(harry.map) // Prints { "name" : "Harry", "age" : 21 }
val tom = User()
tom.name = "Tom"
tom.age = null
print(tom.map) // Prints { "name" : "Tom", "age" : null }
}
abstract class HashMappable {
var map: Map<String, Any?> = mapOf()
}
class HashMappableProperty<T>(initialValue: T) : ReadWriteProperty<HashMappable, T> {
private var value: T = initialValue
override fun getValue(thisRef: HashMappable, property: KProperty<*>): T {
return value
}
override fun setValue(thisRef: HashMappable, property: KProperty<*>, value: T) {
this.value = value
thisRef.apply { map = map + (property.name to value) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment