Kotlin Data Class
In Kotlin, data classes are a concise way to declare classes that are primarily used to hold data.
They automatically generate useful methods such as toString()
: to generate string representation of the object, equals()
: to check if two data class objects are equal, hashCode()
, and copy()
: to copy a data class object. Also, you can override these methods with your own code in the class declaration, if required.
To declare a data class in Kotlin, you use the data
keyword before the class
keyword, and you list the properties of the class in the primary constructor.
For example,
data class Person(val name: String, val age: Int)
In this example, Person
is a data class with two properties: name
and age
. The compiler automatically generates the toString()
, equals()
, hashCode()
, and copy()
methods for you.
Example for Data Class
Now, let see an example program to understand how we can use this data class.
Kotlin Program
data class Person(val name: String, val age: Int)
fun main() {
val person1 = Person("John", 25)
val person2 = Person("Jane", 30)
println(person1) // Output: Person(name=John, age=25)
// Access properties using Destructuring declaration
val (name, age) = person2
println("Name: $name, Age: $age")
// Copying an instance with modified properties
val olderPerson = person1.copy(age = 26)
println(olderPerson)
// Equality check
println("Is person1 equal to person2? ${person1 == person2}")
}
Output
Person(name=John, age=25)
Name: Jane, Age: 30
Person(name=John, age=26)
Is person1 equal to person2? false