Kotlin - Data Classes
we will learn more about Data classes of Kotlin programming language. A class can be marked as a Data class whenever it is marked as ”data”. This type of class can be used to hold the basic data apart. Other than this, it does not provide any other functionality.
All the data classes need to have one primary constructor and all the primary constructor should have at least one parameter. Whenever a class is marked as data, we can use some of the inbuilt function of that data class such as “toString()”,”hashCode()”, etc. Any data class cannot have a modifier like abstract and open or internal. Data class can be extended to other classes too. In the following example, we will create one data class.
fun main(args: Array<String>) { val book: Book = Book("Kotlin", "jeetu", 5) println("Name of the Book is--"+book.name) // "Kotlin" println("Puclisher Name--"+book.publisher) // "Jeetu" println("Review of the book is--"+book.reviewScore) // 5 book.reviewScore = 7 println("Printing all the info all together--"+book.toString()) //using inbuilt function of the data class println("Example of the hashCode function--"+book.hashCode()) } data class Book(val name: String, val publisher: String, var reviewScore: Int)
The above piece of code will yield the following output in the browser, where we have created one data class to hold some of the data, and from the main function we have accessed all of its data members.
Name of the Book is--"Kotlin" Puclisher Name--"jeetu" Review of the book is--5 Printing all the info all together--(name-Kotlin, publisher-jeetu, reviewScore-7) Example of the hashCode function---1753517245
Comments
Post a Comment