https://kotlinlang.org logo
#getting-started
Title
# getting-started
f

fstn

10/09/2017, 5:37 PM
I try to make an extensible User class, this class will be save as JSON and will be updated by JSON
Copy code
data class User(val firstName: String?,
           val lastName: String?,
           val gender: UserGender?,
           val type: UserType?,
           val picture: String?,
           val locale: String?,
           val heart: Int?,
           val level: Int?,
           val timezone: String?
) : JsonObject() {

    init {
        put(User::firstName.name, firstName ?: this[User::firstName.name])
        put(User::lastName.name, lastName ?: this[User::lastName.name])
        put(User::gender.name, gender ?: this[User::gender.name])
        put(User::type.name, type ?: this[User::type.name])
        put(User::picture.name, picture ?: this[User::picture.name])
        put(User::locale.name, locale ?: this[User::locale.name])
        put(User::heart.name, heart ?: this[User::heart.name])
        put(User::level.name, level ?: this[User::level.name])
        put(User::timezone.name, timezone ?: this[User::timezone.name])
    }
}

fun User.update(userUpdate: JsonObject) {
    userUpdate.fieldNames().forEach({ fieldName ->
        this.put(fieldName, userUpdate.getValue(fieldName))
    })
}
Using this, I can Update the class and add dynamically a property cars on my User class by doing:
Copy code
user.update({car:"BMW"})
And I can continue to use user.firstName instead of user.get(“firstName”) What do you thing about this way to do?