-
Notifications
You must be signed in to change notification settings - Fork 23
Kotlin: Class vs DataClass
In Kotlin, a data class is a special class that is specifically designed to hold data. It automatically generates several standard methods such as toString()
, equals()
, hashCode()
, and copy()
. This makes data classes concise and helps reduce boilerplate code when you need a class primarily for storing and representing data.
Here are some key differences between a normal class and a data class in Kotlin:
-
Default Methods: Data classes automatically generate some commonly used methods (mentioned above) for you, whereas in a normal class, you would need to manually implement these methods.
data class Person(val name: String, val age: Int) val person1 = Person("John", 25) val person2 = Person("John", 25) println(person1 == person2) // true (equals() is automatically generated)
-
Component Functions: Data classes automatically provide component functions for properties, which can be useful in certain scenarios, like destructuring declarations.
val (name, age) = person1 // Destructuring declaration using component functions
-
Copy Method: Data classes provide a
copy
method, which allows you to create a copy of an instance with some properties changed.val modifiedPerson = person1.copy(age = 30)
-
Immutability by Default: Data classes make properties immutable by default, making them suitable for representing immutable data.
data class Point(val x: Int, val y: Int)
Here,
x
andy
are automaticallyval
(immutable). -
Inherited Methods: Data classes automatically inherit methods from the
Any
class (the root of the Kotlin type hierarchy), includingtoString()
andhashCode()
. -
No-arg Constructor: Data classes automatically generate a no-arg constructor if all the properties have default values.
data class Student(val name: String = "", val age: Int = 0)
In summary, while a normal class requires manual implementation of commonly used methods, a data class in Kotlin provides them automatically. Data classes are concise and designed for cases where the primary purpose is to hold and represent data.