👨🏼💻Kotlin Data Class
What is the Data Class and what is the difference between data and normal class?
Introduction
Hello Dear Kotlin lovers! Welcome to my new article. Today I’m going to explain Data classes, and explain why we use these data classes instead of regular classes. First, let’s start with the definition of the Data class.
Data class:
Sometimes we may have to create classes in which we can only keep data in the programs that we coded. Likewise, we may have to create functions of certain standards within these classes. Therefore, Kotlin has created data classes to resolve all these concerns. In short, data classes are classes that help us hold data and automatically contain certain standard functions.
Furthermore, we need to pay attention to things when creating the data class. These are as follows;
1-Data classes must take at least 1 parameter.
2- When we form these classes, functions such as equals(), hashCode(), toString(), copy(), componentN() are generated in the background.
When we look at the exact Java equivalent of our Kotlin code above, we can see these automatically generated functions.
3-If we override these automatically generated functions of the data classes and write them ourselves, instead of these automatically generated functions, the functions that we wrote will be written in the background. Additionally, these auto-generated functions only work for variables inside the primary constructor. Variables that we define inside the data class are not included in these custom generated functions.
4-The parameters defined in the primary constructor of the data class must be defined by VAL or VAR. Because functions such as toString(), which are specially generated in the data class, use variables defined in these primary Constructor and need to access these variables. If we define without using Val or Var , these methods cannot access these values, as there will be no access to values within the class.
5-Data classes cannot be open, abstract, sealed, inner class.
6-Data classes have the final keyword by default. Therefore, they cannot be inherited.
7-Although data classes are not inherited, they can inherit from another class or abstract class. Moverover, they can implement interfaces.
8-Data classes allow us to make destructuring declarations with automatically generated componentN functions.
val jane = User("Jane", 35)
val (name, age) = jane
println("$name, $age years of age") // prints "Jane, 35 years of age"
Conclusion
As a result, data classes are structures that enable us to hold data and generate certain functions by default, which are essentially created with sectoral concerns. Furthermore, automatic function creation in the background is the biggest feature that distinguishes it from keeping data in normal class.