Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Data class

Classes that are used to hold data of real world entities (ex. - User, Order, Account) often require to override equals() and toString() function. To save us from this extra code, we have Data classes.

Data class is special type of class that provides additional functionalities helpful for data holding classes.

Data class provides the following functionalities out of the box :

To define a class as Data class, we use the data keyword :

 data class /* className */(...) { ... }
 

Example :

 data class User(
    val id: Int,
    val name: String
)

fun main() {
    val user = User(1, "Ashoka")
    val user1 = User(1, "Ashoka")

    println(user) // Prints "User(id=1, name=Ashoka)"

    println(user == user1) // Prints "true"
}
 

Notice that just by defining the class as data, equality check works as expected and object is converted to a nicely formatted string with all fields of the class. That too without overriding any functions!

We can create a copy of a data class object using copy() function :

 val user = User(1, "Ashoka")

// Create a copy with fields same as that of user
val userCopy = user.copy()

println(user == userCopy) // Prints "true" because fields are equal
println(user === userCopy) // Prints "false" because new copy is created

// Create a copy by changing one or more fields
val newUser = user.copy(name = "Ashoka the great")
println(newUser) // Prints "User(id=1, name=Ashoka the great)"
 

Disadvantage