Subscribe Now

* You will receive the latest news and updates on your favorite celebrities!

Trending News

Blog Post

How to use Data Class in Kotlin?
Kotlin

How to use Data Class in Kotlin?

In this blog, you will learn about How to use Data Class in Kotlin? and What is Data Class?
Tired of writing or generating lengthy, boilerplate code for objects which do nothing but store data?

Kotlin has the solution for you!

Mostly all software project we create has a number of classes which exist to store data or state but have no actual functionality in terms of operations.

All the model/ POJO / data class generally contains the same concept every time:

  • A constructor
  • Fields to store data
  • Getter and setter functions
  • hasCode(), equals() and toString() functions

In JAVA we are writing code for all those operations. It will not get generate automatically. Now let’s check what Kotlin Data Classes offer us.

Data Class in Kotlin

In Kotlin, If you want to create a class that holds data then you can use data keyword with class.
Syntax:

data class (var variable1, var variable2, ....)

For this class, the compiler automatically generates:

  • copy() function, equal() and hashcode() pair, and toString() form of the primary constructor.
  • componentN() functions

This all functions you need to create manually in JAVA.

Example of creating data class in Kotlin:

data class CarModel(var carId:Long, var carColor: String)

Now we will see how we can create an instance of a data class.

An instance of a Data Class

We can create an instance of a data class in the same manner as we do for standard class.

Example:

val carModel = CarModel(1, "Red")

We can now access the members of the CarModel class.

carModel.carId // 1
carModel.carColor // Red
carModel.carColor = "Black" //Assign Black color

Print the contents of the class:

val carModel = CarModel(1, "Red")
Log.i("Car Model Values", carModel.toString())

//Print
//CarModel(carId=1, carColor="Red")

Read-Only Fields in Data Class

If we want some fields in data class remain read-only and no one can assign value to it. Then we can use val instead of var. Below is the example

data class CarModel(var carId: Long, val carColor: String, val carName: String)

In above example, carColor and carName have read access only. Where carId has read/ write access.

copy() Function With Data Class in Kotlin

Many times you have a situation where you need to copy an object altering some of its properties but keeping the rest unchanged. This is what copy() function is generated for.

Example:

val carModel = CarModel(1, "Red")
var audiCarModel = carModel.copy(carColor = "Black")

In the above example, we created audiCarModel using carModel but we just changed carColor value from Red to Black.

Data Classes and Destructuring Declarations

This is the name of the syntax provided by Kotlin which allows us to map an object into individual fields. This is where the componentN() functions stated above come into play.

For each property we specify for our data class, Kotlin will generate a componentN() function which maps to that property.

In our case, Example

carModel.component1() // 1
carModel.component2() // Red

Now, these generated functions allow us to use restructuring declarations to do some cool things.

We can restructure an object to create three val  properties at once:

val carModel = CarModel(1, "Red")
val (carID, theCarColor) = carModel

//val carID == 1
//val theCarColor == "Red"

We can destructure data directly inside a loop through maps/ collections:

val listOfCars = listOf<CarModel>()
        for ((carId) in listOfCars) {
            Log.i("CAR ID = ", carId.toString())
        }

Some Built-in Data Classes in Kotlin

Kotlin also has the build-in data classes Pair and Triple for common operations:

val pair: Pair<Int, String> = Pair(10, "Ten")
val triple: Triple<Int, String, Boolean> = Triple(1, "One", true)

Although as the docs state, in most cases, it is usually better to create your own data class (even if it has 2 or 3 attributes) which has a more descriptive/relevant name for your use case.

Rules for Creating Data Classes in Kotlin

  • The primary constructor needs to have at least one parameter.
  • All primary constructor parameters need to be marked as val or var;
  • Data classes cannot be abstract, open, sealed or inner;
  • Data classes may only implement interfaces (not extend other classes)

Conclusion

Like most other aspects of Kotlin, data classes aim to reduce the amount of boilerplate code you write in your project. Check the official Kotlin Document on Data Classes

You can be in touch with me on Twitter or from the Facebook Android4Dev group.

If you don’t know what is class and object in Kotlin. You can read this blog.

Related posts

Leave a Reply

Required fields are marked *