1) Details On Data Classes
1) Details On Data Classes
fun main() {
Let's say that you have a very simple class. You can compare it to itself, but this comparison
will only return true, if exactly the same instance is on both sides of the comparison. This
means that by default, all objects created with custom classes are considered unique, they
are not equal to any other object.
fun main() {
Printing or transforming an object into a string is also not very useful. The result should be
this class name, @ sign, and some numeric digits. The number is not really useful, it only
helps us know if two objects are the same or not.
println(pluto1) // Dog@404b9385
So, what can you do to get more meaningful data from printing a string? This behavior can
be altered if you use data modifier before a class. You use it before classes representing a
bundle of data. Such a class is equal to a different instance of the same class if its
constructor properties have the same value.
fun main() {
When you transform a data class into a string, you not only have this class name, but also
values for each constructor property.
println(pluto1) // Dog(name=Pluto)
That is not all. Data classes can be destructured, which means reading values from this
class and assigning them to variables.
data class Dog(val name: String,val age: Int)
println(name) // Pluto
println(age) // 7
Beware that destructuring in Kotlin is based on position, not name, so value names need to
be placed at correct positions. For instance, if you place age at the position of name, and
name at the position of age, then you will have age in a variable called name, and name in
the variable called age.
To prevent this, always check if your variables are assigned to the correct positions of
constructor parameters.
Finally, data classes have a copy method, that creates a copy of an object. It also allows you
to specify what modifications you would like to introduce into an object.
fun main() {
You use data modifiers for classes that are used to represent a bundle of
data. Such classes are quite common in programming.