Hello everyone, today I am talking about the data class and simple class in the kotlin. So in order to do that I will simply differentiate between them and when we should use which class. We frequently create classes whose main purpose is to hold data. In such a class some standard functionality and utility functions are often mechanically derivable from the data. In Kotlin, this is called a data class and is marked as data
. So let’s simply discuss them!
What is class?
The class declaration consists of the class name, the class header, and the class body, surrounded by curly braces. class header specifying its type parameters, the primary constructor, etc. Both the header and the body are optional; if the class has no body, curly braces can be omitted.
“class Invoice { /…/ }
“
data classes have to fulfill the following requirements:
- The primary constructor needs to have at least one parameter;
- All primary constructor parameters need to be marked as
val
orvar
; - Data classes cannot be abstract, open, sealed or inner;
- (before 1.1) Data classes may only implement interfaces.
Things we additionally have in data class
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.
Properties Declared in the Class Body
Note that the compiler only uses the properties defined inside the primary constructor for the automatically generated functions. To exclude a property from the generated implementations, declare it inside the class body:
Only the property name
will be used inside the toString()
, equals()
, hashCode()
, and copy()
implementations, and there will only be one component function component1()
. While two Person
objects can have different ages, they will be treated as equal.
val person1 = Person("John") val person2 = Person("John") person1.age = 10 person2.age = 20
Copying
It’s often the case that we need to copy an object altering some of its properties, but keeping the rest unchanged. This is what copy()
function is generated for. For the User
class above, its implementation would be as follows:
fun copy(name: String = this.name, age: Int = this.age) = User(name, age)
This allows us to write:
val jack = User(name = "Jack", age = 1) val olderJack = jack.copy(age = 2)
Data Classes and Destructuring Declarations
Component functions generated for data classes enable their use in destructuring declarations:
val jane = User("Jane", 35) val (name, age) = jane println("$name, $age years of age") // prints "Jane, 35 years of age"
Summary
So after reading this blog you are able to differentiate between kotlin normal class and data class. Basically in the data class, we have some extra methods like hashcode, copy, etc.
References
https://kotlinlang.org/docs/reference/
https://www.programiz.com/kotlin-programming/data-class
https://www.geeksforgeeks.org/kotlin-data-classes/