I'm of course excluding any reasons that involve violating the rules for what can be a data class. So if you know you won't need to inherit from it for example (although it's my understanding that rule is going away in Kotlin 1.1).
There are following conditions for a Kotlin class to be defined as a Data Class: The primary constructor needs to have at least one parameter. All primary constructor parameters need to be marked as val or var. Data classes cannot be abstract, open, sealed, or inner.
Answer: Kotlin provides a special type of class called data class, which is usually used for objects that act as a store for data properties and has no business logic or member functions. It provides a lot of advantages with reduced boilerplate code.
A data class is a class that only contains state and does not perform any operation. The advantage of using data classes instead of regular classes is that Kotlin gives us an immense amount of self-generated code.
Data Class Limitations They can't be open , abstract , sealed or inner classes. The compiler forbids manually implementing copy() and componentN() methods. Any parent interface or class of a data class must not have a copy() method.
data
modifier makes Kotlin generate common methods like toString
, hashCode
, equals
for the most commons (%80) scenarios based on the primary constructor.
This shows 3 reasons why only few classes should be data
:
Most non-data classes have a mix of properties defined in the primary constructor and in the body of the class. Also the primary constructor often has parameter that are not fields (but help initialise more complex fields in the body). In other words, data
has very restrictive requirements which are rarely met by regular classes.
In addition to point 1, making a class data
may hurt its extensibility. Even if the layout of the class in question conforms to the rules of data
classes, later someone may want to add another property in the body of the class. In that case he will have to manually override hashCode
because it may be used somewhere.
Marking a class data
sends a message to the one who reads the code that you intend to use this class as a data career. Marking other classes will be misleading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With