Professional Documents
Culture Documents
Motivation
this.id = id;
this.name = name;
return id;
this.id = id;
}
public String getName() {
return name;
this.name = name;
@Override
@Override
return result;
}
}
You see, for creating a Simple class with only two member fields, we
had to write almost 50 lines of code.
Yes, I know that you don’t need to write that code yourself and any good
IDE can generate all that boilerplate code for you.
But that code will still be there in your source file and clutter it. Moreover,
whenever you add a new member field to the Class, you’ll need to
regenerate/modify the constructors, getters/setters and
equals()/hashcode() methods.
You can also use a third party library like Project Lombok to
generate getters/setters , equals()/hashCode() , toString() m
ethods and more. But there is no out of the box solution without any
library that can help us avoid these boilerplate codes in our application.
Kotlin has a better solution for classes that are used to hold data/state.
It’s called a Data Class. A Data Class is like a regular class but with
some additional functionalities.
With Kotlin’s data classes, you don’t need to write/generate all the
lengthy boilerplate code yourself. The compiler automatically generates
a default getter and setter for all the mutable properties, and a getter
(only) for all the read-only properties of the data class. Moreover, It also
derives the implementation of standard methods
like equals() , hashCode() and toString() from the properties
declared in the data class’s primary constructor.
For example, The Customer class that we wrote in the previous section
in Java can be written in Kotlin in just one line -
data class Customer(val id: Long, val name: String)
// Getting a property
Since all the properties of the Customer class are immutable, there is
no default setter generated by the compiler. Therefore, If you try to set a
property, the compiler will give an error -
// Setting a Property
# Output
/*
Copies the customer object into a separate Object and updates the name.
*/
println("Customer : $customer")
# Output
println(customer.component1()) // Prints 4
// Destructuring Declaration
Data classes help us avoid a lot of common boilerplate code and make
the classes clean and concise. In this article, you learned how data
classes work and how to use them. I hope you understood the all the
concepts presented in this article.
Thank you for reading folks. See you in the next post!