Kotlin has introduced many features, in this post we will focus on data class.
data – A type of class that mainly use for hold a data. in such class, some standard functionality and utility functions are often mechanically derivable from the data. we called data class in kotlin.
In case of data class compiler automatically derives the following members from all properties declared in the primary constructor:
# componentN() functions corresponding to the properties in their order of declaration.
# copy() function
data classes have to fulfill the requirements:
# The primary constructor needs to have at least one parameters.
# All primary constructor parameters need to be marked as val or var.
# Data classes cannot be abstract, open, sealed or inner.
# (before 1.1) Data classes may only implement interface
let see the example of data class.
Now we are going to create a class with data prefix and define a primary parameterized constructor.
data class Customer(var id: Int,var name: String,var email : String) //or you can define with default value data class Customer(var id: Int,var name: String="",var email : String="email@example.com")
In the next step, we will be going to instantiate our customer class and print the customer object by using toString method.
var customer = Customer(1,"Nikesh","firstname.lastname@example.org") println(customer.id) println(customer.name) println(customer.email) println(customer.toString()) output: 1 Nikesh email@example.com Customer(id=1, name=Nikesh, firstname.lastname@example.org)
Now we will compare customer object using the equals method.
var customer = Customer(1,"Nikesh","email@example.com") var customer1 = Customer(1,"Nikesh","firstname.lastname@example.org") println(customer.equals(customer1)) customer1 = Customer(1,"Ritesh","email@example.com") println(customer.equals(cus=tomer1)) output: true false
Note – Structural equality is checked by the equal/
== operation and referential equality is checked by the
We can Copy one object in another by using copy method.
var customer = Customer(1,"Nikesh","firstname.lastname@example.org") var customer1 = customer.copy(2,"Ritesh") println(customer1.id) println(customer1.name) println(customer1.email) output: 2 email@example.com Ritesh
using componentN (Destructuring declarations)
val (_,name,email) = customer
above syntax is called a destructuring declaration. A destructuring declaration creates multiple variables at once. we have declared two new variables name and email and can use them independently.
let’s take look example.
var customer = Customer(1,"Nikesh","firstname.lastname@example.org") val (_,name,email) = customer // println(id) println(name) println(email) output: Nikesh email@example.com
Ref – Kotlin docs
Thanks for reading 🙂Follow @nikeshpathak