How do I use data classes in Kotlin to store structured data?
In Kotlin, data classes are designed to store structured data with minimal boilerplate. A data class automatically provides useful functions such as: toString() equals() hashCode() copy() component functions for destructuring, like component1(), component2() Basic example data class User( val id: Int, val name: String, val email: String ) You can create and use it like […]
Artikel oleh Wayan · Sumber: Kode Java ↗
Terjemahan artikel ini belum tersedia. Isi asli ditampilkan.
In Kotlin, data classes are designed to store structured data with minimal boilerplate.
A data class automatically provides useful functions such as:
toString()equals()hashCode()copy()- component functions for destructuring, like
component1(),component2()
Basic example
data class User(
val id: Int,
val name: String,
val email: String
)
You can create and use it like this:
fun main() {
val user = User(
id = 1,
name = "Alice",
email = "alice@example.com"
)
println(user)
}
Output:
User(id=1, name=Alice, email=alice@example.com)
Accessing properties
println(user.name)
println(user.email)
Because the properties are declared in the primary constructor, they are available directly.
Comparing data objects
Data classes compare values, not object references:
val user1 = User(1, "Alice", "alice@example.com")
val user2 = User(1, "Alice", "alice@example.com")
println(user1 == user2) // true
Copying with changes
Use copy() to create a modified copy:
val updatedUser = user.copy(email = "newalice@example.com")
println(updatedUser)
The original object is unchanged.
Destructuring
Data classes support destructuring declarations:
val (id, name, email) = user
println(id)
println(name)
println(email)
Mutable vs immutable properties
Prefer val for immutable data:
data class Product(
val id: Long,
val name: String,
val price: Double
)
Use var only if the property needs to change:
data class MutableUser(
var name: String,
var age: Int
)
Example with nested structured data
data class Address(
val street: String,
val city: String,
val postalCode: String
)
data class Customer(
val id: Int,
val name: String,
val address: Address
)
fun main() {
val customer = Customer(
id = 100,
name = "Maria",
address = Address(
street = "Main Street",
city = "Berlin",
postalCode = "10115"
)
)
println(customer.address.city)
}
Important rules
A Kotlin data class must:
- Have at least one parameter in the primary constructor
- Mark primary constructor parameters with
valorvar - Not be
abstract,open,sealed, orinner
Example:
data class Book(
val title: String,
val author: String,
val year: Int
)
Use data classes when you mainly need a class to hold data rather than define complex behavior.
