equals()
, hashCode()
, toString()
, copy()
, and componentN()
functions for property access.
To define a data class, you simply specify the property names, their types, and optional initial values in the primary constructor.
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}") }
In the above example: - The
Employer
class is declared as a data class.
- The primary constructor defines two properties: companyName
and marketValueInBillions
.
- When an instance of the Employer
class is created, the compiler automatically provides implementations for the standard functions.
This approach enhances code readability and reduces boilerplate, making Kotlin particularly well-suited for data modeling.