1.

What are data classes in Kotlin? Explain with a proper example.

Answer»

The Data class is a simple class that holds data and PROVIDES typical functions. To declare a class as a data class, use the data keyword. 

Syntax:

data class className ( list_of_parameters)

The following functions are automatically derived by the COMPILER for the data classes:

  • equals() - The equals() function returns true if two objects have the identical CONTENTS. It operates similarly to "==," ALTHOUGH for Float and Double values it works differently.
  • hashCode() - The hashCode() function returns the object's hashcode value.
  • copy() - The copy() function is used to DUPLICATE an object, changing only a few of its characteristics while leaving the rest unaltered.
  • toString() - This function returns a string containing all of the data class's parameters.

To ensure consistency, data classes must meet the following requirements:

  • At least one parameter is required for the primary constructor.
  • val or var must be used for all primary constructor parameters.
  • Abstract, open, sealed, or inner data classes are not possible.
  • Only interfaces may be implemented by data classes.

Example:

data class Sample(var input1 : Int, var input2 : Int)

The above code snippet creates a data class Sample with two parameters.

fun main(agrs: Array<String>) { val temp = Sample(1, 2) println(temp) } 

Here, we create an instance of the data class Sample and pass the parameters to it.

Output:-

Sample(input1=1, input2=2)


Discussion

No Comment Found