Last active
December 8, 2019 04:08
-
-
Save HarryTylenol/aa7945c5faaa6abc6e9b6a7ce59dc1d7 to your computer and use it in GitHub Desktop.
Auto HashMappable Object with Kotlin (Thanks to Property Delegation!)
This file contains 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
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 } | |
} |
This file contains 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
abstract class HashMappable { | |
var map: Map<String, Any?> = mapOf() | |
} |
This file contains 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
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