Techoceanhub logo

What is data class in Kotlin- Chapter-7

We have made classes in Java, in the same manner, there are classes in Kotlin  as well but they are fully known as Data Classes in kotlin.

A data class is something that holds data for us. These types of data class holds data in it and do not encapsulate any additional logic. 

Now let us see a simple example of data class in kotlin.

package adapter.manasvi.com.dataproject

class Person( var name:String, var mobilenumber: Int) {
fun main(agrs: Array<String>) {
val obj1 = Person("Ashi", 1235796)//first object
val obj2 = Person("Nishi", 45623231) //second object
if (obj1 == obj2) {
println("equal")
} else {
println("unequal")

}
}
}

As we can see in the above simple example data class will always start with the keyword data. Kotlin data class automatically inbuilt some built-in functions like:-

  • equals():Boolean
  • hashcode():Int
  • toString():String
  • copy()
  • componentN()

All of the methods are very common methods but there is a method which is not very common is componentN(), let us define what this method does for us in kotlin.

The componentN()  the function is another example of the principle of conventions widely used in Kotlin. Anything can be on the right-hand side of a destructuring declaration, as long as the required number of component functions can be called on it LIKE component1(), component2(). And, of course, there can be and so on. The functions need to be marked with the keyword to allow using them in a destructuring declaration.

Now overall let us see a simple straightforward interactive video to illustrate a simple data class in kotlin. 

Feel free to comment below and subscribe.

Share:

Categories

Archives

Related Posts

Array Destructuring

Array Destructuring Array destructuring is a powerful syntax introduced in ES6 that allows you to unpack elements from an array

Read More »

Explore our Affiliated partner links

hostgator website plan

Hostgator

Best Website hosting plans & Best for 24/7 support.

hostinger webhosting plan

Hostinger

Reasonable website hosting packages for small business & 24/7 Email support

Elementor pro

Design Worpdress website quickly using Elementor Builder and AI

buy elementor website templates

Buy Elementor Website Template

Buy ready made Elementor Website Template from us & Get Free Elementor pro licence for 1 year .