Sunday, May 6, 2018

Kotlin - Data Classes

In Java, We always create model(POJO) classes for hold data/state. These classes generally contain the same old boilerplate code in the form of getters, setters, equals(), hashcode() and toString() methods and increase number of line code of every class.
User class in Java that just holds id and name of a user and doesn’t have any functionality.
Java Class
public class User {                                                                        
    private String id;
    private String name;
    public User (String id, String name) { = id; = name;
    public String getId() {
        return id;
    public void setId(String id) { = id;
    public String getName() {
        return name;
    public void setName(String name) { = name;
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User ) o;
        if (id != null ? !id.equals(user .id) : user .id != null) return false;
        return name != null ? name.equals(user .name) : == null;
    public int hashCode() {
        int result = id != null ? id.hashCode() : 0;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
As we can see a simple class with only two member fields. We had to write almost 50 lines of code. If you going to create such classes in Java that will increase LOC(Line of code) of Project. If you want to add a new member field to the class, you’ll need to regenerate/modify the constructors, getters/setters and equals()/hashcode() methods. That's is time-consuming.

I know that we can use lots of plugins. You don’t need to write that code yourself and generate all that boilerplate code for you. But that code will still be there in your source file.

Kotlin has a solution for these classes that are used to hold data/state. It’s called

A Data Class is like a regular class but with some additional functionalities. You can mark the class as data to create a data class.
Kotlin data class
data class User(var id: Int, val name: String)
For this class, the compiler automatically do.
1. It avoids all the boilerplate of getters and setters.
2. equals() / hashCode().
3. A set of functions that called componentX().
4. A copy() method, very useful with immutable objects.
5. toString() form of the primary constructor.

Let's talk about the requirements that a data class need.
1. The primary constructor must have at least one parameter.
2. All the parameters declared in the primary constructor need to be marked as val or var.
3. Data classes cannot be abstract, open, sealed or inner.
4. Data classes may not extend other classes (but may implement interfaces).

Let's see, How you can use the standard methods on the above data class.

1. Data class’s equals() method

Example - 1 
  val user1 = User(1, "LIBS")
  val user2 = User(1, "LIBS")
We can also use equality(==) operator to check for equality. The == operator internally calls the equals() method.
Example - 2 
 println(user1 == user2) 
2. Data class’s toString() method
The toString() method converts the object to a String in the form of "ClassName(field1=value1, field2=value2)"
Example - 3 
 val user= User(2, "LIBS")
 println("User details : $user")
 User details : User(id=2, name=LIBS)
3. Data class’s hashCode() method
Example - 4 

 val user= User(2, "LIBS")
 println("User HashCode :- ${user.hashCode()}") 
 User HashCode :-1841845792
4. Data Classes and Immutability: The copy() function

Let assume we have a situation, Where we need to create an immutable class.
Kotlin Immutable class
data class Person(val name: String, val age: Int)
Immutable objects are easier to work with and reason about while working with multi-threaded applications. They can not be modified after creation, you don’t need to worry about concurrency issues that arise when multiple threads try to modify an object at the same time.

Now, I wish to change some data. We can do it with the help of copy() function. We can copy an existing object into a new object and modify some of the properties while keeping the existing object unchanged.

Example - 5
val user = User(3, "LIBS")
//Now we can modify any property of object.
val updatedUser = user.copy(name = "LIBS TEAM")
println("User: $user")
println("Updated User: $updatedUser")
User: User(id=3, name=LIBS)
Updated User: User(id=3, name=LIBS TEAM)
6. Data Classes componentN() functions.
Kotlin allows us to map an object with individual fields. Kotlin generates two componentN() functions. We can use these properties with component1() and component2() corresponding to the id and name properties.
Example - 6
val user= User(4, "LIBS")
7. Destructuring Declarations.
It helps you destructure an object into a number of variables like.
Example - 7
val user= User(2, "LIBS")
// Destructuring Declaration
val (id, name) = user
println("id = $id, name = $name")
"id = 4, name = LIBS"
We can destructure data directly inside a loop through maps/collections:
Example - 8
val listOfUser: List<User> = listOf(id, name)
for ((id, name) in listOfUser) {
This is very useful when dealing with key/value stores.

8. Some Built-in Data Classes.
Kotlin also has the built-in data classes Pair and Triple for common operations:
Example - 9
val pair: Pair<Int, String> = Pair(10, "Ten")
val triple: Triple<Int, String, Boolean> = Triple(1, "One", true)

<<Previous                                                                                            Next>>


Get it on Google Play

Android - Scoped storage OS 11

Every Android updated version has something for developers and users alike. The Android 10 version has many user-friendly and performance en...