Data classes in Kotlin are a feature designed to hold data and automate common operations like equals, hashCode, toString, and copy. They're part of Kotlin's commitment to reducing boilerplate code, making data handling easier and more intuitive.
When to Use Data Classes
- When you need a class primarily for storing data, without any significant behavior.
- When you want concise and consistent implementations of
equals,hashCode,toString, andcopymethods. - In scenarios like representing records, transferring data across layers, or modeling entities in domain logic.
How to Declare a Data Class
Declaring a data class is simple. Use the data keyword before the class keyword.
data class Person(val name: String, val age: Int)This declaration automatically provides equals, hashCode, toString, and copy methods, alongside them being val (read-only) properties by default.
Generated Methods
equals and hashCode
The equality operator == and hashCode method are overridden to ensure two instances of a data class are equal if all properties are equal.
toString
The toString method is overridden to provide a string representation like Person(name=John, age=30).
copy
You can create a new instance by copying an existing data class object with some properties modified.
val person1 = Person("Alice", 29)
val person2 = person1.copy(age = 30)This creates person2 by copying person1 and changing age.
Destructuring Declarations
Data classes automatically declare componentN() functions for properties, allowing for destructuring declarations:
val jane = Person("Jane", 23)
val (name, age) = jane
println(name) // Output: Jane
println(age) // Output: 23Limitations & Restrictions
- Primary constructor needs at least one parameter.
- All primary constructor parameters need to be marked as
valorvar. - Cannot be
abstract,open,sealed, orinner.
Conclusion
Data classes streamline data management tasks in Kotlin programs, offering a succinct, expressive syntax for transforming and processing data. Prioritize them when you need a class to simply hold data and handle typical operations, allowing you to focus on the core logic of your application without additional boilerplate code.