What is the difference between a normal class and a data class in Kotlin?

Most of the time we developers use class to keep only data in classes. Classes have some methods which needs to be overridden wrt the data it holds. ex: hashCode(), equals().

Data classes automatically take care of such utilities.

From the official documentation:

We frequently create a class to do nothing but hold data. In such a class some standard functionality is often mechanically derivable from the data. In Kotlin, this is called a data class and is marked as data.

The compiler automatically derives the following members from all properties declared in the primary constructor:

  • equals()/hashCode() pair,
  • toString() of the form “User(name=John, age=42)”,
  • componentN() functions corresponding to the properties in their order of declaration,
  • copy() function (see below).
    If any of these functions is explicitly defined in the class body or inherited from the base types, it will not be generated.

To read more, check data-classes

About the result, Technically, you are getting is different because of implementation of toString() method. data class’ toString() method uses data class properties and values to form returning string. General class’ toString() method uses hash code to form returning string.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)