Skip to content

Kotlin: Object Class vs Data Object Class

Devrath edited this page Aug 8, 2024 · 1 revision

To understand a data object class, we need to understand what a data class is.

In Kotlin, the object and data object are both related to singleton objects, but they serve different purposes and have distinct features. Here's a comparison:

object

  • Singleton: The object keyword in Kotlin is used to create a singleton, which means only one instance of the class will exist. It's useful for creating single instances like utility classes or globally accessible objects.
  • No Automatic Methods: When you declare an object, it doesn't automatically generate any methods like equals(), hashCode(), or toString(). You can override these methods if needed.
  • Initialization: The object is initialized lazily, the first time it is accessed.

Example:

object MySingleton {
    val name = "Singleton"
    
    fun printName() {
        println(name)
    }
}

data object

  • Singleton with Data Features: The data object is a specialized form of an object that also behaves like a data class. It automatically generates equals(), hashCode(), and toString() methods, making it more suitable when you want a singleton with data class-like behavior.
  • Immutability: Just like data classes, data object ensures that the singleton is immutable, and its properties are generally val.
  • Ideal for Use Cases: It's ideal for cases where the singleton holds state or is compared/used in collections.

Example:

data object MyDataSingleton {
    val id = 1
    val name = "DataSingleton"
}

Summary

  • Use object when you need a simple singleton without automatic data class features.
  • Use data object when you want a singleton with the benefits of a data class, such as equals(), hashCode(), and toString() methods.
Clone this wiki locally