Kotlin Data Classes

Kotlin Data Classes

Hey, welcome again to my blog! Today, we shall learn more about Kotlin Data Classes and if you have missed any of my previous tutorials in this series, kindly check them out here.

We learnt about Enum classes in the previous blog.

What are Data Classes?

Data classes, as the name suggests, are classes that are meant to hold data.

A data class helps create some boilerplate code for us as we shall see.


To make a data class, we simply add data in front of a normal class.

data class Person(val name: String, val id_no: Int)

Before we move on, there are rules considered in order to create data classes in Kotlin: These are;
酪he primary constructor needs to have at least one parameter.
農ll primary constructor parameters need to be marked as val or var.
道ata classes cannot be abstract, open, sealed or inner.
道ata classes may only implement interfaces.


data class Movie(var name: String, var studio: String, var rating: Float)

As I said, when we create a data class in Kotlin, the following methods are automatically created by the compiler:


A data class is instantiated the same way as other classes: From our example, let's instantiate from it.

val movie = Movie("Free Guy", "Sony Pictures", 8.5F)

toString() method
The toString() function returns a string representation of the object. Example:



Movie(name=Free Guy, studio=Sony Pictures, rating=9.0)

copy() method
For a data class, you can create a copy of an object with some of its properties different using copy() function.

Here's how it works:

val movie2 = movie.copy(name = "Avengers")

When we print above:


We get:

Movie(name=Avengers, studio=Sony Pictures, rating=8.5)

hashCode()and equals() methods

The hasCode() method returns hash code for the object. If two objects are equal, hashCode() produces the same integer result. Recommended Reading: hashCode()

The equals() returns true if two objects are equal (has same hashCode()). If objects are not equal, equals() returns false. Recommended Reading: equals()

data class Movie(var name: String, var studio: String, var rating: Float)
val movie = Movie("Free Guy", "Sony Pictures", 8.5F)

fun main(){
    val movie2 = movie.copy(name = "Avengers")
    val movie3 = movie.copy()

    println("movie hashcode = ${movie.hashCode()}")
    println("movie hashcode = ${movie2.hashCode()}")
    println("movie hashcode = ${movie3.hashCode()}")

    if (movie.equals(movie2) == true)
        println("movie is same as movie2")
        println("movie is not same as movie2")

    if (movie.equals(movie3) == true)
        println("movie is same as movie3")
        println("movie is not the same as movie3.")

The above is full code with the previous method examples and if we ran the code: The output for the above methods should be:

movie hashcode = 951067529
movie hashcode = 456663247
movie hashcode = 951067529
movie is not same as movie2
movie is same as movie3

componentN() method
Component functions generated for data classes make it possible to use them in destructuring declarations:

movie.component1() //  Free Guy 
movie.component2() // Sony Pictures
movie.component3() // 8.5

If we added this code in our main function above to restructure declarations:

val movie4 = Movie("Dr Strange", "Marvel", 9.5F)
val (name, studio, rating) = movie
println(println("$name has a rating of $rating !!"))

Our Expected Output: Dr Strange has a rating of 9.5 !!

Python Data Classes

Data classes were introduced in Python 3.7 (and backported to Python 3.6), providing a handy way to make classes less verbose.

To install Data classes: pip install dataclasses Example:

from dataclasses import dataclass

class MyArticle():
    """A class for holding an article content"""

    # Attributes Declaration
    # using Type Hints

    title: str
    author: str
    language: str
    upvotes: int

# A DataClass object
article = MyArticle("Data Classes",
                    "Ronnie A",
                    "Kotlin", 1)

Expected Output:

MyArticle(title='Data Classes', 
                 author='Ronnie A', 


Data classes are just regular classes that are geared towards storing state, rather than containing a lot of logic. Every time you create a class that mostly consists of attributes, you make a data class.

For More Reading, I will recommend:

Programmiz Article
kotlin Docs
Geeks For Geeks Article
Data Classes In Python: Official Docs

If you enjoyed reading, consider subscribing and reacting to this with love by sharing, commenting and any criticism is much welcome.

達ollow me on Twitter :

Ronnie Atuhaire