What is the difference between a normal class and a data class in Kotlin?
for a data class.
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).
see https://kotlinlang.org/docs/reference/data-classes.html
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.
A class
represents some data "type" and its behaviour(s) so from that point of view data class
isn't any different than a class
. But there are certain behaviours and rules about a data class
that makes it a bit different:
- Calling
toString()
on a data class dumps a string with all its member properties. - It has
componentN
method thatget
member properties by their ordern
. - It has a
copy
method which takes the member properties as parameters for making a diff copy of the object. - A
data class
can not be open. Cant be inherited. - It can not be
abstract
. - It can not be
nested
,inner
orsealed
. - Although it can inherit, define abstract methods and implement interfaces.
data class
properties can be destructed into individual variables e.gval (name, address) = Person("name", "address")
Pair(a, b)
internally usesdata class
.