Google News
logo
Kotlin - Interview Questions
What are data classes in Kotlin and how are they different from regular classes?
In Kotlin, data classes are a special type of class that are primarily used to hold and represent data. They provide a concise way to declare classes whose main purpose is to store data and provide commonly needed functionalities. Here are the key characteristics and differences of data classes compared to regular classes:

1. Default Functionality :
   * Data classes automatically provide implementations for common functions such as `equals()`, `hashCode()`, `toString()`, and `copy()`. These functions are generated by the compiler based on the properties defined in the primary constructor of the data class.
   * This default functionality saves developers from writing boilerplate code for these commonly used operations.

2. Property Declaration :
   * Data classes allow property declaration directly in the primary constructor.
   * The properties defined in the primary constructor are automatically treated as immutable (val) properties.
  
    Example :
     data class Person(val name: String, val age: Int)​
3. Comparison and Copying :
   * Data classes provide an automatic implementation of the `equals()` function, which compares the values of properties for equality.
   * The `hashCode()` function is also generated based on the properties of the data class, ensuring that equal objects have the same hash code.
   * The `copy()` function is generated, allowing you to create a copy of an existing data class instance with the option to modify some properties.

4. Component Functions :
   * Data classes generate component functions (`component1()`, `component2()`, etc.) that allow destructuring declarations to extract properties easily.
   * This enables syntax like `val (name, age) = person` to extract values into individual variables.

5. Inheritance and Interfaces :
   * Data classes can inherit from other classes and implement interfaces, just like regular classes.
   * However, if a data class explicitly defines any of the functions (`equals()`, `hashCode()`, or `toString()`) or uses `copy()` with named arguments, the compiler won't generate them automatically.

6. Customization :
   * Developers can override the generated functions with custom implementations if needed.
   * Custom properties and functions can be added to data classes as well.
Advertisement