Using the data class

The data class is one of the most popular features among Kotlin developers. It is similar to the concept of the Model class. 

The compiler automatically derives the following members from all properties declared in the primary constructor:

  • The equals()/hashCode() pair
  • The toString() of the User(name=John, age=42) form 
  • The componentN() functions corresponding to the properties in their order of declaration
  • The copy() function 

A simple version of the data class can look like the following line of code, where name and age will become properties of a class:

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

With this single line and, mainly, with the data keyword, you get equals()/hasCode(), toString() and the benefits ...

Get Kotlin Blueprints now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.