InterviewSolution
Saved Bookmarks
| 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:
To ensure consistency, data classes must meet the following requirements:
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) |
|