In Kotlin, data classes are a special type of class that are primarily used to hold data, and are often used for data transfer. Data classes can be defined using the ‘data‘ keyword before the class keyword.
The main difference between a data class and a regular class is that data classes are automatically generated with certain methods and functionality that are useful for handling data. Some of the features that come with data classes are:
Automatic generation of equals() and hashCode() methods.
Automatic generation of toString() method.
Automatic copying of objects using the copy() method.
Automatic generation of component methods for destructuring declarations.
Here is an example of a regular class and a data class:
// Regular Class
class Car(val make: String, val model: String, val year: Int) {
fun start() {
println("Starting the $make $model")
}
}
// Data Class
data class Car(val make: String, val model: String, val year: Int)
In the above example, the ‘Car‘ class is defined first as a regular class, and then as a data class. Notice that the second definition is much shorter, as most of the behavior is automatically generated by the Kotlin compiler.
Now, let’s consider the following code:
val car1 = Car("Toyota", "Camry", 2020)
val car2 = Car("Toyota", "Camry", 2020)
println(car1 == car2) // false
val car3 = car1.copy(year = 2021)
println(car3) // Car(make=Toyota, model=Camry, year=2021)
In the above code, we create three instances of ‘Car‘: ‘car1‘, ‘car2‘, and ‘car3‘. Notice that even though ‘car1‘ and ‘car2‘ have the same values for their properties, they are not considered equal. This is because the ‘equals()‘ method is not implemented for the regular ‘Car‘ class. However, when we use the data class ‘Car‘, ‘equals()‘ is automatically generated, and so ‘car1‘ and ‘car2‘ are considered equal.
Lastly, we use the ‘copy()‘ method to create a new instance of ‘Car‘, with the same values as ‘car1‘, except with a year of 2021. This is useful because it allows us to modify an instance of ‘Car‘ without having to manually copy all of its properties. Again, this method is automatically generated for data classes.