Skip to content

Kotlin: Class vs DataClass

Devrath edited this page Dec 24, 2023 · 11 revisions

In Kotlin, a data class is a special class that is specifically designed to hold data. It automatically generates several standard methods such as toString(), equals(), hashCode(), and copy(). This makes data classes concise and helps reduce boilerplate code when you need a class primarily for storing and representing data.

Here are some key differences between a normal class and a data class in Kotlin:

  1. Default Methods: Data classes automatically generate some commonly used methods (mentioned above) for you, whereas in a normal class, you would need to manually implement these methods.

    data class Person(val name: String, val age: Int)
    
    val person1 = Person("John", 25)
    val person2 = Person("John", 25)
    
    println(person1 == person2) // true (equals() is automatically generated)
  2. Component Functions: Data classes automatically provide component functions for properties, which can be useful in certain scenarios, like destructuring declarations.

    val (name, age) = person1 // Destructuring declaration using component functions
  3. Copy Method: Data classes provide a copy method, which allows you to create a copy of an instance with some properties changed.

    val modifiedPerson = person1.copy(age = 30)
  4. Immutability by Default: Data classes make properties immutable by default, making them suitable for representing immutable data.

    data class Point(val x: Int, val y: Int)

    Here, x and y are automatically val (immutable).

  5. Inherited Methods: Data classes automatically inherit methods from the Any class (the root of the Kotlin type hierarchy), including toString() and hashCode().

  6. No-arg Constructor: Data classes automatically generate a no-arg constructor if all the properties have default values.

    data class Student(val name: String = "", val age: Int = 0)

In summary, while a normal class requires manual implementation of commonly used methods, a data class in Kotlin provides them automatically. Data classes are concise and designed for cases where the primary purpose is to hold and represent data.

Clone this wiki locally