
Data Classes in Kotlin
📌 Data Classes in Kotlin
In Kotlin, a data class is a special type of class used to store data. It automatically provides useful functions like equals()
, hashCode()
, toString()
, and copy()
without needing to write boilerplate code.
✅ 1. Defining a Data Class
Use the
data
keyword before theclass
declaration.Must have at least one primary constructor parameter.
Commonly used for data models or DTOs (Data Transfer Objects).
📌 Syntax:
data class User(val name: String, var age: Int)fun () { val user1 = User("Alice", 25) val user2 = User("Bob", 30) println(user1) // Output: User(name=Alice, age=25) println(user2) // Output: User(name=Bob, age=30)}
✅ 2. Features of Data Classes
Data classes in Kotlin provide the following built-in functions:
🔎 a. toString()
Provides a readable string representation of the object.
println(user1.toString()) // Output: User(name=Alice, age=25)
🔎 b. equals()
and hashCode()
Automatically compares object properties instead of references.
val user3 = User("Alice", 25)println(user1 == user3) // Output: true
hashCode()
generates a unique code based on property values.
🔎 c. copy()
Creates a copy of the object, with the option to modify specific properties.
val user4 = user1.copy(age = 26)println(user4) // Output: User(name=Alice, age=26)
✅ 3. Data Class with Functions
You can also add functions to a data class.
data class Product(val name: String, var price: Double) { fun () { println("Product: $name, Price: $fun () { val product = Product("Laptop", 1200.0) product.displayInfo()}
Output:
Product: Laptop, Price: $1200.0
✅ 4. Component Functions with Data Classes
Data classes provide component functions (component1()
, component2()
, etc.) to access properties. This is useful for destructuring.
📌 Example: Destructuring Declaration
val (name, age) = User("Charlie", 28)println("Name: $name, Age: Name: Charlie, Age: 28
✅ 5. Data Class with Default Values
You can provide default values to constructor parameters.
data class Employee(val name: String = "Unknown", val salary: Double = 30000.0)fun main() { val emp1 = Employee() val emp2 = Employee("John", 45000.0) println(emp1) // Output: Employee(name=Unknown, salary=30000.0) println(emp2) // Output: Employee(name=John, salary=45000.0)}
✅ 6. Limitations of Data Classes
Data classes cannot be abstract, open, sealed, or inner.
Data classes must have at least one parameter in the primary constructor.
✅ Conclusion
Data Classes are ideal for storing and representing data.
They provide built-in functionality like
toString()
,equals()
,copy()
, andhashCode()
.Use destructuring declarations for easy property access.
Ideal for use in API responses, database entities, or DTOs.