Promptless AI is here soon - Production-ready contextual code. Don't just take our word for it. Know more
Know More
Education

Kotlin Data Classes: A Smarter Way to Hold Data

No items found.
logo

DhiWise

July 13, 2021
image
Author
logo

DhiWise

{
July 13, 2021
}

Summary:

Kotlin is the most favored language for Android application development. It has a plethora of advanced features that save developers time and help to improve app quality by removing boilerplate code. Kotlin Data Class is one of the best features among them. 

Know more about it.

kotling-data-classes

Choosing the best programming language for your tech stack is a real challenge. There are multiple technologies available in the market, but Java and Kotlin are the most preferred for Android development, though each one of them has its pros and cons. 

f you are more concerned about faster development with less complexity and fewer errors, Kotlin will always win.

In this article, we'll look at one of the most popular Kotlin features, Kotlin Data Classes, which can help you reduce the number of lines of code and improve the efficiency of developing your Android app compared to Java.  Want to know how? Let’s compare through the example below.

When we develop an Android application in Java, we create POJO classes that look something like this:

//A typical POJO (Plain Old Java Object)
 
public class Book {

    private int id;
    private String title;
    private String description;
    private String content;
    private String author;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", description='" + description + '\'' +
                ", content='" + content + '\'' +
                ", author='" + author + '\'' +
                '}';
    }
}

This appears to be an excessive amount of code for a class that only holds data. In Kotlin, the same model class can be represented as,

// Data class Book in Kotlin

data class Book(
        var id: Int,
        var title: String,
        var description: String,
        var content: String,
        var author: String
) 

Based on the preceding example, we can conclude that Kotlin removes the majority of the boilerplate code, resulting in clean and concise code. With lesser code, there are fewer chances of errors and therefore Kotlin is preferred over Java by Android Developers.

But still, you might be curious about how the data is accessed here without getter and setter methods. The answer is, everything is generated automatically. 

To understand more about Data classes and how it works let’s start from the basics.

What is Data Class in Kotlin?

A data class is used to store information or state. It also contains some standard functionality and utility functions that are frequently derived from the data. In Kotlin, a data keyword is used to declare the Data class, as shown in the code sample below.

data class Person(val name: String)

The data keyword is used to notify the compiler that you are creating this class to hold data. As a result, the compiler generates a number of functions/methods from the Data Class. It consists of the following methods:

  • equals()/ hashCode() pair
  • toString() 
  • componentN() 
  • copy() 

Some crucial requirements for creating Kotlin Data Classes

Following are the rules and requirements for implementing data classes to ensure consistency and meaningful behavior of the generated code. 

  1. The primary constructor of Data Class must have at least one parameter.

For example, Person(val name: string) is valid but Person () is invalid.

  1. All the primary constructors must be indicated as val or var.

For example, Person(name: string) is invalid.

  1. Data Classes can not be marked as abstract, sealed, open, or inner.
  2. Data Class member generation follows these rules as a result of member inheritance.

Methods in Kotlin Data Classes

1. hashCode(): It is used to return the hash code value for the object. 

2. equals(): The method returns true if two objects have the same content and it works similarly to “==”.

For example, equals() returns true if the hashCode() is equal, else it returns false in output as shown in the code sample below. 

 

3. toString(): This method returns a string of all the parameters which are defined in the data class.

 //   Data Class method: toString()

fun main(args: Array<String>) 
{
    //declaring a data class 
    data class obj(val id: Int, val name: String)
   
    //declaring a variable of the above data class 
    //and initializing values to all parameters
   
    val obj1=obj(1, "obj")
       
    //printing all the details of the data class
    println(obj1.toString());  // output:  obj(id=1, name=obj)

}

The explicit implementation of the functions equal(), hashCode(), or toString() in the data class body or final implementation in the superclass will restrict the auto-generation of the same class and only the existing implementations will be used.

4. copy()

The copy method is used to duplicate an object in the data class.  As a result, you can modify some or all of its properties.  Immutable objects make multi-threaded applications easier to use.  Therefore it is suggested to apply the val parameter in the data class to use the immutable properties of an object. 

// Data Class method: copy()
 
data class Customer(var name: String, var id: Int)
fun main(agrs: Array<String>)
 {  
   val obj = Customer("John Doe", 777)  
   println(obj)  // output: Customer(name=John Doe, id=777)
   val copyObj = obj.copy()  
   println(copyObj)  // output: Customer(name=John Doe, id=777)
}

5. componentN()

Sometimes it is convenient to destructure an object into several variables. componentN() method enables us to access each of the arguments specified in the data class constructor as a property so you can use each property independently. 

Here N defines the number of parameters in the constructor.

// Data Class method: componentN()

data class Customer(var name: String, var id: Int)
fun main(agrs: Array<String>) {
val obj = Customer("John Doe", 777)  
   println(customer.component 1()) // output: John Doe
   println(customer.component2()) // output: 777

}

If the variable is declared in private then the destructuring is not allowed.

Conclusion

Every developer strives to create a bug-free application. Unfortunately, this is not always possible.  Building an Android application with Java can increase the number of lines of code as compared to Kotlin.  The greater the number of lines of code, the greater the possibility of errors in the application.

Kotlin removes most of the boilerplate code with its advanced features and one of them is Data classes. Data classes automatically generate some methods rather than manually create them, which saves development time and helps to build apps faster.  

Role of DhiWise

DhiWise is an ultra-modern platform for web and mobile application development, that enables developers to build clean and lightweight apps faster without compromising the code quality. 

It provides support for widely used software technologies such as Node.js, Flutter, React.js, Laravel, Swift, and Kotlin with advanced features to simplify app development so that you can wrap your month’s work in weeks.  

Accelerate your Android application development with DhiWise, know about its Android App Builder.

Sign up for free!

Happy coding!!

Frequently asked questions

Frequently asked questions

No items found.