I’m new to Kotlin, and have found the awesome Data Class!
So, I’m using Data Classes to get some information from a JSON API, but I’d like to process the data before using it to save some time/processing power.
To make things easier, I’ll illustrate an easy example:
data class UserApi(val name: String, val born: Int)
As I said, I'm receiving the data from a JSON API, but creating a User programmatically would look like this:
val userApi: UserApi = UserApi("Catelyn", 1990)
Now, instead of calculating how old the User is every time by:
"currentYear - userApi.born" // Calculating an approximate age
Ofc without changing the API, I’d just like to get an immutable val like this:
userApi.age
Is this possible? I’m thinking something like:
interface UserApi {
val name: String
val born: Int
}
data class User(override val name: String, override val born: Int) : UserApi {
// Calculating an approximate age
val age: Int = "currentYear - userApi.born"
}
val user: User = User("Catelyn", 1990) // Or get the data from an API.
// Getting the age of the User like this:
user.age // Same as "currentYear - userApi.born".
Is something like this the way to go?
You can mix in additional property into your data class:
data class UserApi(val name: String, val born: Int) {
val age get() = LocalDate.now().year - born
}
val mikesAge = UserApi("Mike", 1990).age
This property will be automatically calculated every time it's accessed.
See the "custom getter" example here.
Or you can just define the new property. This property will be calculated only once:
data class UserApi(val name: String, val born: Int) {
val age = LocalDate.now().year - born
}