What is a Data Class in Kotlin?
A Kotlin class can be declared as a data class using the data keyword. This instructs the compiler to automatically generate several standard methods:
equals()— for structural equality checkshashCode()— for use in hash-based collectionstoString()— for a readable string representationcopy()— for creating modified copies of instancescomponentN()— for destructuring declarations
Requirements for a Kotlin Data Class:
- The primary constructor must have at least one parameter, and each parameter must be marked as val or var.
- The class cannot be marked as open, abstract, sealed, or inner.
- The class can extend other classes or implement interfaces.
Example of a Kotlin Data Class:
data class Employer(val companyName: String, val marketValueInBillions: Int)
fun main() {
val employer = Employer("TechCorp", 4)
println("Company Name: ${employer.companyName}")
println("Market Value (in billions): ${employer.marketValueInBillions}")
}
- The
Employerclass is declared with thedatakeyword. - It contains two properties:
companyNameandmarketValueInBillions. - The compiler automatically generates useful methods like
equals(),hashCode(),toString(), andcopy().
This approach improves code readability and maintainability. Kotlin data classes are ideal for modeling simple data structures such as database entities, API response models, or UI state.