Difference Between Class and Data Class in Kotlin

1. Introduction

In Kotlin, understanding the distinction between class and data class is key for efficient programming. 

A class in Kotlin is a blueprint for objects that can hold both data and behaviors. It's a traditional OOP concept used to encapsulate data and functionality. 

A data class, however, is a concise way to create classes that primarily serve as holders of data. In Kotlin, data classes come with several built-in functionalities like equals(), hashCode(), and toString().

2. Key Points

1. Primary Purpose: Regular classes are general-purpose, and data classes are optimized for holding data.

2. Built-in Functions: Data classes automatically generate equals(), hashCode(), and toString(), among others.

3. Mutability: Both can have mutable (var) and immutable (val) properties.

4. Copy Functionality: Data classes have a built-in copy() function.

3. Differences

Characteristic Class Data Class
Primary Purpose General-purpose Holding data
Built-in Functions Manually implemented Automatically generated
Mutability Both mutable and immutable properties Both mutable and immutable properties
Copy Functionality Manually implemented Built-in copy() function

4. Example

// Example of a Class
class Person(val name: String, val age: Int) {
    fun greet() {
        println("Hello, my name is $name.")
    }
}

// Example of a Data Class
data class User(val name: String, val age: Int)

Output:

Class Output:
Person object with name and age, custom greet method.
Data Class Output:
User object with name and age, auto-generated `toString()`, `equals()`, `hashCode()`, and `copy()`.

Explanation:

1. Person is a regular class with a custom method greet(). It represents a more traditional approach with manually implemented functionalities.

2. User is a data class that automatically generates utility functions like toString(), equals(), and hashCode(), making it ideal for classes that primarily serve as data holders.

5. When to use?

- Use a regular class when you need to define objects that encapsulate both data and behaviors and when you need more control over the implementation.

- Use a data class when your primary goal is to store data, and you want to take advantage of Kotlin's built-in functionalities for data handling, such as automatic toString() or copy() methods.

Comments