Kotlin - Data Classes


In this chapter, 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", "TutorialPoint.com", 5)
   println("Name of the Book is--"+book.name) // "Kotlin"
   println("Puclisher Name--"+book.publisher) // "TutorialPoint.com"
   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--"TutorialPoint.com"
Review of the book is--5
Printing all the info all together--(name-Kotlin, publisher-TutorialPoint.com, reviewScore-7)
Example of the hashCode function---1753517245

Useful Video Courses


Kotlin Online Training

68 Lectures 4.5 hours

Arnab Chakraborty


Kotlin Masterclass Programming: Android Coding Bible


71 Lectures 5.5 hours

Frahaan Hussain


Android Dependency Injection using Dagger with Kotlin

18 Lectures 1.5 hours

Mahmoud Ramadan


Android Retrofit complete course in Kotlin

49 Lectures 6 hours

Catalin Stefan


Master Kotlin - Learn Kotlin to develop android apps

49 Lectures 2.5 hours



Breeze Music Player - Learn Kotlin, MVVM and MediaPlayer API

22 Lectures 1 hours