DEV Community

Discussion on: Kotlin - The Good, the Bad and the Ugly

Collapse
 
vishnuharidas profile image
Vishnu Haridas • Edited

Data classes are very useful when declaring POJOs for processing JSON, with some extensions. For example, I can have the below setup to fetch a JSON that contains a user's data and convert it into the App's user model to remember locally in my app:

data class UserResponse(id: String, email: String, name: String){
fun asAppUser() = AppUser(name, id, email) // Convert to App's model.
val isVerified: Boolean
get() = id.endsWith("-unverified") // for example, id="37823-unverified"
}

// Somewhere in code,
val jsonString = fetchUserDataFromServer()
val user = Gson().fromJson(jsonString, UserResponse::class)

if(user.isVerified){
rememberUser(user.asAppUser())
}