T E C h O C E A N H U B

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 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.

Copyright ©TechOceanhub All Rights Reserved.