Some properties of a class might be common for all of its objects. For example, consider a class Employee to save data of employees that belong to one organization only. So organization property will have only one value which won’t change. Then defining it as a data member leads to inefficient memory usage because it has to be saved in memory separately for each and every object.
data class Employee(
val id: Int,
val name: String,
val organization: String = "ABC Enterprises"
)
fun main() {
val a = Employee(1, "A")
val b = Employee(2, "B")
println(a) // Prints "Employee(id=1, name=A, organization=ABC Enterprises)"
println(b) // Prints "Employee(id=2, name=B, organization=ABC Enterprises)"
}
Here each object has its own copy of organization
field although its value is same for each object. Hence inefficient memory usage due to duplicate data.
A minor problem
A minor problem
Notice that organization is defined as constructor argument. So, while creating an object we can define a custom value for it :
val a = Employee(1, "A", "DEF Consultancy")
This is bad design. We can fix this problem, by defining organization
inside the class body :
data class Employee(
val id: Int,
val name: String
) {
val organization: String = "ABC Enterprises"
}
Since it is defined as val
, we can’t even modify it (precisely what we want!).