Sling Academy
Home/Kotlin/What Are Data Classes in Kotlin? A Beginner's Guide

What Are Data Classes in Kotlin? A Beginner's Guide

Last updated: December 05, 2024

In Kotlin, data classes provide a neat way to handle data without having to write a lot of boilerplate code. Introduced to simplify classes that are solely used to hold data and provide some utilities, they come with features like auto-generated functions such as toString(), equals(), and copy(). This guide aims to give beginners a comprehensive understanding of Kotlin data classes and how to use them.

What is a Data Class?

A data class in Kotlin is a class primarily used to hold data/state and comes with a few predefined functions. These functions include:

  • toString() - Provides a string representation of the object.
  • equals() - Checks structural equality.
  • hashCode() - Returns a hash code value for the object.
  • copy() - Creates a copy of the object.

Defining a Data Class

To define a data class in Kotlin, use the keyword data before the class signature. Here's a simple example of a data class:

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

In this example, User is a data class with two properties: name and age. When defined, Kotlin automatically provides implementations for the mentioned methods.

Basic Operations with Data Classes

Let's see how you can create objects and what operations you can perform with data classes in Kotlin.

fun main() {
    val user1 = User("Alice", 30)
    val user2 = User("Bob", 28)

    println(user1) // Output: User(name=Alice, age=30)

    // Use of equals and hashCode
    println(user1.equals(user2)) // Output: false

    val user3 = user1.copy(age = 31)
    println(user3) // Output: User(name=Alice, age=31)
}

In this example, we create a new User object. Notice how toString() is automatically implemented, making it easier to print an object. The copy() function allows you to clone an instance, changing specific parameters.

Component Functions

Data classes automatically generate component functions for every property in the class below is an example usage:

fun main() {
    val user = User("John", 25)
    val (name, age) = user
    println("Name: $name, Age: $age")
}

This syntax is called destructuring declarations, and it is a convenient way to unpack data easily from an object.

Requirements and Restrictions

There are a few constraints when creating a data class in Kotlin. Those are:

  • The class must have at least one primary constructor parameter.
  • All primary constructor parameters need to be marked as val or var.
  • Data classes cannot be abstract, open, sealed, or inner.

Use Cases of Data Classes

Data classes are especially useful in situations where you need a concise and lightweight way to model attributes, for instance, in:

  • Domain models: Representing data structures retrieved from JSON APIs or databases.
  • Immutable structures: Providing immutability which can be particularly useful in concurrent programming.
  • UI State: Holding state in state management libraries.

Conclusion

Data classes are an integral part of Kotlin, offering a streamlined way to handle data-centric objects without unnecessary overhead. Their simplicity in designing equals methods, convenient copy functions, and more, help developers focus on defining data structures rather than the unexciting details of handling object comparison, printing, or state duplication. Now that you understand data classes, try implementing them in your next Kotlin project to see how they can simplify your data model design.

Next Article: When and How to Use Data Classes in Kotlin

Previous Article: Difference Between Abstract Classes and Interfaces in Kotlin

Series: Kotlin Object-Oriented Programming

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin