Thuta Learning
IntermediateProgrammingbeginner

Data Classes

Relax. We'll talk through this in plain words — no textbook voice.

A data class is a class designed mainly to hold data. In Kotlin, data keyword makes the compiler generate toString(), equals(), hashCode(), copy() and other useful functions automatically. It's used all the time in API response models, database row models, and UI state models.

kotlin
data class User(val name: String, val age: Int)

fun main() {
    val user1 = User("Alice", 28)
    val user2 = user1.copy(name = "Bob")

    println(user1)
    println(user2)
}
You should see
User(name=Alice, age=28) User(name=Bob, age=28)

Summary

Data classes are a great Kotlin feature for writing model objects short and clean.

Easy traps

  • It's easy to mix up a normal class with a data class. If your class's main job is holding data, a data class is the better choice.

Practical example — article model

Practical example — article model

kotlin
data class Article(val title: String, val published: Boolean)

fun main() {
    val draft = Article("Kotlin Tutorial", false)
    val publishedPost = draft.copy(published = true)

    println(publishedPost)
}

You'll know it worked when: Article(title=Kotlin Tutorial, published=true)

Data Classes | Thuta Learning