Classes, objects and data classes

You will understand the structural difference between blueprint classes, singleton objects, and specialized data classes used for state management. About 25 minutes.

Why it matters

  • An object lives as long as the process. A singleton that holds an Activity, a View or another short-lived object keeps it in memory: a classic Android leak.
  • Data classes are the usual shape for UI state in Compose and ViewModels, because value equality lets the UI skip work when nothing changed.
  • Interviewers use equals/hashCode behavior to test your knowledge of object identity vs equality.
  • Knowing when to use companion object is essential for factory patterns and constants.

The simple explanation

  • A class is a blueprint for a house. You can build as many houses from it as you like.
  • An object is a one-off building: there is no blueprint to reuse, and exactly one exists.
  • A data class is a standardized shipping container: two containers with the same contents count as the same.

In Kotlin, a class is a template. When you instantiate it, you create an instance in memory.

object declarations in Kotlin are singletons. On the JVM the instance is created the first time the object is accessed, and that initialization is thread-safe. This is useful for constants or stateless utilities. A companion object is a singleton tied to a specific class, often used to hold factory methods or static-like members.

data class is a specialized class designed to hold data. The compiler automatically generates equals(), hashCode(), toString(), copy(), and componentN() functions from the properties declared in the primary constructor.

Featureclassdata classobject
PurposeGeneral logic/behaviorHolding state/dataSingleton instance
== by defaultReference (inherited from Any)Compares primary constructor propertiesOnly one instance exists
InstantiationVia constructorVia constructorAutomatic, on first access

Warning: Data classes must have at least one primary constructor parameter, and every primary constructor parameter must be marked val or var, otherwise the code does not compile. If you use a regular class to hold data, list.contains(item) returns false for a different instance with the same properties, because it uses equals().

Notes

  • class defines a blueprint; object is a singleton instance.
  • data class provides automatic equals() and hashCode() based on primary constructor properties.
  • Use copy() in data classes to create modified versions of immutable state.
  • From Kotlin, companion object members are called on the class name, like Java statics. From Java you need Companion. unless the member is const, @JvmStatic or @JvmField.
  • Data classes cannot be abstract, open, sealed, or inner.
  • Initialization of an object is thread-safe. Its mutable state is not: concurrent writes to a var inside an object still need synchronization.
  • Prefer val in data classes used as UI state, so every change goes through copy().
  • The generated equals(), hashCode() and toString() only use properties declared in the primary constructor.

Code example

This code demonstrates the difference between a standard class, a singleton object, and a data class used for state.

data class UserState(val id: Int, val name: String) // Immutable state
 
class UserSession(val token: String) { // Logic class
    companion object {
        const val SESSION_TIMEOUT = 3600
    }
}
 
object DatabaseManager { // Singleton
    fun connect() = "Connected"
}
 
fun main() {
    val state1 = UserState(1, "Alice")
    val state2 = UserState(1, "Alice")
 
    // Data class equality check
    println(state1 == state2) // true
 
    // Copying state for updates
    val state3 = state1.copy(name = "Bob")
    println(state3.name) // Bob
 
    // Singleton access
    println(DatabaseManager.connect())
 
    // Companion object access
    println(UserSession.SESSION_TIMEOUT)
}
  • UserState uses val to ensure the state cannot be mutated after creation.
  • DatabaseManager is an object, so there is exactly one instance in the process.
  • UserSession.SESSION_TIMEOUT demonstrates how to group constants within a class scope.

Run the idea in plain Kotlin

class Person(val name: String)
data class Product(val id: Int, val price: Double)
object AppConfig {
  val version = "1.0.0"
}

fun main() {
  val p1 = Person("John")
  val p2 = Person("John")
  println("Person equality: " + (p1 == p2)) // false, reference equality

  val prod1 = Product(101, 29.99)
  val prod2 = Product(101, 29.99)
  println("Product equality: " + (prod1 == prod2)) // true, value equality

  val updatedProd = prod1.copy(price = 19.99)
  println("New price: " + updatedProd.price)

  println("App Version: " + AppConfig.version)
}

In production

List flickers on every refresh
  • Every time the feed refreshed, all rows in a RecyclerView flashed, even rows whose content had not changed.
  • The adapter was a ListAdapter whose DiffUtil.ItemCallback implemented areContentsTheSame as oldItem == newItem.
  • The row model was a regular class. Each refresh mapped the network response into new instances, so == fell back to reference equality and returned false for every row.
  • DiffUtil reported every row as changed, so every row was rebound and played a change animation.
The fix
  • Reproduce with a unit test: map the same response twice and assert that the two rows are equal. It fails before the fix.
  • Convert the row model to a data class with val properties, so == compares content.
  • Keep areItemsTheSame comparing a stable id, and let areContentsTheSame use the generated equals().
  • Verify that only rows with changed data are rebound after a refresh.

Common mistakes

  • Using var in data classes. If you mutate a property after putting the object in a HashSet or using it as a HashMap key, its hashCode() changes and lookups stop finding it. It also lets state change without going through copy().
  • Defining properties outside the primary constructor in a data class. Properties defined in the body are not used for equals(), hashCode(), toString() or copy().
  • Using object for things that need multiple instances. It creates a singleton, meaning you can never have two different versions of that object.
  • Forgetting val in data class constructor. The code will not compile; data classes require constructor parameters to be val or var.
  • Using class for DTOs (Data Transfer Objects). Comparing two DTOs from a network response with == returns false even if the data is identical.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between a class and a data class?”

“What is a singleton in Kotlin?”

“How does the copy() function work in a data class?”

“What is a companion object?”

Quiz

Which of these is NOT automatically generated by a data class?

What happens if you define a property in the body of a data class instead of the primary constructor?

Class Config has a companion object with const val VALUE = 1. How do you access it from Kotlin code outside the class?

What is the primary purpose of the 'object' keyword in Kotlin?

0 of 4 answered

Mini task

Task: State Management Refactor

  1. Create a data class named Task with two properties: id (Int) and title (String).
  2. Create an object named TaskRepository that contains a single property repositoryName (String) set to "MainRepo".
  3. In a main function:
    • Create two different instances of Task with the same id and title.
    • Print whether the two instances are equal using ==.
    • Create a third Task instance by using the .copy() method on the first instance, changing only the title.
    • Print the new title.
    • Print the repositoryName from the TaskRepository object.

Done Condition: The program must print true for the equality check and correctly show the updated title and the repository name.

Next: Sealed classes, enums and when