In this post we will discuss Data classes with example.
- We frequently create a class to do nothing but hold data. Kotlin provides similar concept, called data class and marked as data.
- When we use data class the primary constructor only accepts property variables such as val or var not parameters.
- The compiler automatically derived the following members from all properties declared in the primary constructor
- We have to follow some rules before creating data classes.
1) The primary constructor must have at-least one parameter.
2) All parameters of primary constructor must be val or var.
3) Data classes cannot be abstract, open, sealed or inner.
4) It not extends other classes but implements interfaces.
- The tostring(), equals(), hashcode() methods of Any superclass is also provided to data class.
- It also provide copy() method to copy parameters of one object in to other. If we have to give different value for some parameter, we pass name and its value into this method.
data class people(var id:Int, var name:String)
We declare a people data class in above example. In main function we create two objects of people data class p1, p2 with same values for parameter and we check if that are equal, it returns equal because the main goal of data class is to deal with only data. If this is not data class it returns unequal. Data class by default provide tostring() method implementation. We create another object of people class and copy p1 object and override name of p1 for p2 object.