Kotlin Data classes

Armen Galstyan
3 min readMay 3, 2021

--

For Data classes, the compiler automatically generates:

  • copy() function, equals() and hashCode() pair, and toString() form of the primary constructor
  • componentN() functions

Kotlin Data Class Requirements

Here are the requirements:

  • The primary constructor must have at least one parameter.
  • The parameters of the primary constructor must be marked as either val (read-only) or var (read-write).
  • The class cannot be open, abstract, inner or sealed.
  • The class may extend other classes or implement interfaces. If you are using Kotlin version before 1.1, the class can only implement interfaces.

When you declare a data class, the compiler automatically generates several functions such as toString(), equals(), hashcode() etc behind the scenes. This helps to keep you code concise. Had you used Java, you would need to write a lot of boilerplate code.

Copying

For a data class, you can create a copy of an object with some of its properties different using copy() function.

toString() method

The toString() function returns a string representation of the object.

hashCode() and equals()

The hasCode() method returns hash code for the object. If two objects are equal, hashCode() produces the same integer result. Recommended Reading: hashCode()

The equals() returns true if two objects are equal (has same hashCode()). If objects are not equal, equals() returns false. Recommended Reading: equals()

Destructuring Declarations

You can destructure an object into a number of variables using destructing declaration.

This was possible because the compiler generates componentN() functions all properties for a data class.

Conclusion

Data classes are one of the most used Kotlin features and for a good reason they decrease the boilerplate code you need to write, enable features like destructuring and copying an object.

--

--

Armen Galstyan
Armen Galstyan

Responses (1)