Hi Everyone,
Hope you like my earlier post on Kotlin (Java to kotlin part-1, java to kotlin part-2 and spring 5 reactive application using kotlin).
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:
#equals()/hashCode() pair.
# toString()
# 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="test@gmail.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","test@nikeshpathak.com") println(customer.id) println(customer.name) println(customer.email) println(customer.toString()) output: 1 Nikesh test@nikeshpathak.com Customer(id=1, name=Nikesh, email=test@nikeshpathak.com)
Now we will compare customer object using the equals method.
var customer = Customer(1,"Nikesh","test@nikeshpathak.com") var customer1 = Customer(1,"Nikesh","test@nikeshpathak.com") println(customer.equals(customer1)) customer1 = Customer(1,"Ritesh","test@nikeshpathak.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 ===
operation.
We can Copy one object in another by using copy method.
var customer = Customer(1,"Nikesh","test@nikeshpathak.com") var customer1 = customer.copy(2,"Ritesh") println(customer1.id) println(customer1.name) println(customer1.email) output: 2 test@nikeshpathak.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.
println(name) println(email)
let’s take look example.
var customer = Customer(1,"Nikesh","test@nikeshpathak.com") val (_,name,email) = customer // println(id) println(name) println(email) output: Nikesh test@nikeshpathak.com
Ref – Kotlin docs
Thanks for reading 🙂
Follow @nikeshpathak