Kotlin Data Class

Kotlin Data Class is defined using the data keyword before the class declaration. It’s primarily used to hold data and comes with several automatically generated functions such as toString(), equals(), hashCode(), and component functions. Let’s delve into the key aspects of Kotlin data classes.

Kotlin Data Class Requirements

A data class in Kotlin must fulfill the following requirements:

  • The primary constructor must have at least one parameter.
  • The parameters of the primary constructor must be marked as either val (read-only) or var (read-write).
  • The class cannot be open, abstract, inner, or sealed. It can extend other classes or implement interfaces.

Example: Kotlin Data Class

data class Person(val name: String, var age: Int)

In this example, Person is a data class with two properties: name (read-only) and age (read-write).

Usage Example and Output

Let’s demonstrate the usage of a data class with a simple example:

fun main() {
    val manoj= Person("Manoj", 30)
    println("name = ${manoj.name}")
    println("age = ${manoj.age}")
}

Output:

name = Manoj
age = 30

Features of Kotlin Data Class

Copying Objects

You can create a copy of an object with some properties modified using the copy() function generated for data classes.

Example:

val person1 = Person("Alice", 30)
val person2 = person1.copy(name = "Bob")
println(person1)  // Output: Person(name=Alice, age=30)
println(person2)  // Output: Person(name=Bob, age=30)

toString() Method

The toString() function returns a string representation of the object.

Example:

val person = Person("Alice", 30)
println(person.toString())  // Output: Person(name=Alice, age=30)

3. hashCode() and equals()

The hashCode() method returns a hash code for the object, while equals() checks if two objects are equal based on their properties.

Example:

val person1 = Person("Alice", 30)
val person2 = person1.copy()

println(person1.hashCode())
println(person2.hashCode())
println(person1 == person2)  // Output: true

4. Destructuring Declarations

You can destructure a data class object using destructuring declarations to extract its properties.

Example:

val person = Person("Alice", 30)
val (name, age) = person
println("name = $name, age = $age")  // Output: name = Alice, age = 30

Real-World Example: Employee Management System

Consider an employee management system where we need to store employee details such as name, ID, and department. A data class can be used effectively in this scenario.

data class Employee(val name: String, val employeeId: Int, val department: String)

fun main() {
    val employee1 = Employee("John Doe", 101, "IT")
    val employee2 = employee1.copy(name = "Jane Doe")

    println(employee1)
    println(employee2)
}

Output:

Employee(name=John Doe, employeeId=101, department=IT)
Employee(name=Jane Doe, employeeId=101, department=IT)

Real-World Application: Library Management System

Now, let’s apply the Book data class in a library management system.

Scenario: Library Management System

In a library, we want to keep track of books with their titles, authors, and available quantities.

Data Class Usage

fun main() {
    // Create instances of Book
    val book1 = Book("The Great Gatsby", "F. Scott Fitzgerald", 5)
    val book2 = Book("To Kill a Mockingbird", "Harper Lee", 3)
    val book3 = Book("1984", "George Orwell", 7)

    // Display book details
    displayBookDetails(book1)
    displayBookDetails(book2)
    displayBookDetails(book3)
}

fun displayBookDetails(book: Book) {
    println("Title: ${book.title}")
    println("Author: ${book.author}")
    println("Available Quantity: ${book.quantity}\n")
}

Output:

Title: The Great Gatsby
Author: F. Scott Fitzgerald
Available Quantity: 5

Title: To Kill a Mockingbird
Author: Harper Lee
Available Quantity: 3

Title: 1984
Author: George Orwell
Available Quantity: 7

Explanation

  • We create instances of the Book data class to represent books in the library.
  • The displayBookDetails function is used to print the details of each book.

Benefits of Kotlin Data Classes

  1. Concise Code: Data classes eliminate boilerplate code for common operations like toString(), equals(), and hashCode().
  2. Easy Data Manipulation: You can copy and modify data class instances easily using the copy() function.
  3. Readability: Data classes improve code readability by clearly defining the structure of data objects.
Kotlin data classes provide a concise and effective way to represent data structures in your code. By leveraging the automatic functionalities generated for data classes, developers can reduce boilerplate code and improve code readability. Understanding and utilizing Kotlin data classes is crucial for building maintainable and efficient Kotlin applications.