KOTLIN TIP #4

 

DATA CLASSES

Data classes simplify classes, adding equals(), hashCode(), copy(), and toString() methods automatically. They clarify the intention of the model and what should go in it, separating pure data from business logic.

Take a look at this data class as an example:

data class User(val name: String, val age: Int)

That’s it. Nothing else is needed to make this class work. If you are using data classes with something like Gson or another JSON parsing library, you can create the default constructor with default values like so:

// Example with Gson's @SerializedName annotation
data class User(
@SerializedName("name") val name: String = "",
@SerializedName("age") val age: Int = 0
)

 

Leave a comment