Kotlin Data classes
For Data classes, the compiler automatically generates:
copy()
function,equals()
andhashCode()
pair, andtoString()
form of the primary constructorcomponentN()
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) orvar
(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.