Kotlin Data Class
In Kotlin, a data class is a special type of class that is designed to store data, without any additional functionality. Data classes are used to define classes that hold data and provide functionality like equals(), hashCode(), toString(), and copy() automatically. Data classes can also be used in destructuring declarations and in combination with the Kotlin standard library functions for collection manipulation.
Here's an example of a data class in Kotlin:
data class Person(val name: String, val age: Int)
In this example, we define a data class called Person
with two properties: name
of type String
and age
of type Int
. Because this is a data class, the equals()
, hashCode()
, toString()
, and copy()
methods are automatically generated for us.
To create an instance of a data class, we use the constructor like any other class:
val person = Person("John", 30)
In this example, we create a new instance of the Person
class with the name "John" and age 30.
We can also use destructuring declarations to extract the values of the properties of a data class:
val (name, age) = person println("$name is $age years old")
In this example, we use a destructuring declaration to extract the name
and age
properties of the person
instance.
Data classes are commonly used to represent structured data, such as records in a database, configuration settings, or data transferred between systems. They simplify the creation of classes that hold data and provide useful functionality for working with that data.