Data Classes In Kotlin

Learn via video courses
Topics Covered

Overview

This article covers the basics of data classes in Kotlin. Starting from the introduction this article delves into basic functions, properties, and examples for the reader to be well-equipped. The article is concluded then with a brief MCQ section that tests the knowledge of the readers

Data classes

It is common practice to design classes with data storage as their primary function. Such classes frequently allow for the mechanical derivation of some utility and standard functionality from the data. These are known as data classes in Kotlin and are identified by the data:

All of the properties declared in the primary constructor are automatically derived by the compiler to yield the following members:

  1. toString() with the format User(name=John, age=42)
  2. equals()/hashCode() pair
  3. copy() function (discussed further in this article)
  4. component() functions corresponding to the properties in their order of declaration.

The following conditions must be satisfied by data class in kotlin to guarantee consistency and purposeful behavior of the created code:

  • At least one parameter must be included in the main constructor.
  • A value or a variable must be specified for each primary constructor argument.
  • Abstract, open, sealed, or inner data classes are not allowed.

In addition, the generation of data class members adheres to the following inheritance rules:

Equals(), hashCode(), and toString() are not generated if they are explicitly implemented in the data class body or have final implementations in a superclass; instead, the existing implementations are used.

When a supertype contains open componentN() functions that return compatible types, the data class automatically generates corresponding functions that override those in the supertype. However, if the supertype functions cannot be overridden because of incompatible signatures or because they are marked as final, an error will be generated.

The componentN() and copy() functions cannot have explicit implementations.

Data classes can extend other classes

If the produced class must have a constructor without parameters on the JVM, default values for the properties must be specified

A Kotlin Data Class is instantiated the same way as other Kotlin classes:

Code:

Output:

Explanation: As we saw in the above example, the Book class has following properties:

  1. name: It represents the name of the book, is of type string and is unmutable
  2. publisher: It represents the publisher of the book, is of type string and is unmutable
  3. reviewScore: It represents review score of the book, is of type int and is mutable

Rules to Create Data Classes

To ensure consistency, data classes must adhere to the following requirements:

  1. There must be at least one parameter in the main constructor.
  2. A value or a variable must be specified for each primary constructor argument. Data classes cannot be inner, sealed, or abstract.
  3. Data classes are limited to implementing interfaces.

Properties Declared in the Class Body

The primary constructor's properties are the only ones that the compiler utilizes when generating functions automatically. Declare a property inside the body of the class to exclude it from the automatically produced implementations:

Only the property name will be used inside the toString(), equals(), hashCode(), and copy() implementations, and there will only be one component function component1(). While two Person objects can have different ages, they will be treated as equal.

Copying

Sometimes we need to duplicate an object while changing only a few of its properties while leaving the rest unaltered. The copy() function is used in this situation.

Properties of copy()

  • All arguments or members defined in primary constructor are copied
  • Two objects can have same primary parameter values and different class body values if defined

Declaration of copy()

The format for defining user is user(String, Int) User here is a data class clearly.

Let's look at an example

Code:

Output:

toString()

A Kotlin Data Class is automatically formed when the toString() function is called. The function's output is a string that represents the object.

Code:

Output:

Note: For the automatically created functions, the compiler only uses the properties specified in the primary constructor. The attributes that are listed in the class body are not included.

Code:

Output:

Explanation: Here height is not used by the toString() function .

hashCode() and equals()

The object's hash code is returned by the hasCode() function. HashCode() delivers the identical integer value for two items if they are equal.

If two objects are equal or have the same hasCode value, the equals() function returns true; otherwise, it returns false.

Declaration of hashCode()

Properties of hashCode()

  • Two hash codes that are declared twice on the same object will have the same value.
  • The returned hash code will be the same if 2 objects are equal as per the equals() method

Code:

Output:

Explanation:

woman1 and woman2 have same object contents, so they are equal, thus they have same hash code values.

Data Classes and Destructuring Declarations

We can destructure an object into a number of variables using destructing declaration.

Code:

Output:

Explanation: Becuase of the component functions provided, it becomes easy to emply data class in kotlin for destructuring declarations Let's see it in action with an example

Code:

Output:

Explanation:

Default and Named Arguments in Data Class

In the primary constructor of the data class in kotlin default arguments can be assigned and can be changed later in the program if required

Code:

Output:

Explanation:

Standard Data Classes

The Pair and Triple classes are available in the standard library. However, named data class in kotlin are typically a superior design decision since they provide meaningful names for the attributes, which improves the readability of the code.

For the need to return multiple values of different datatypes a function might need multiple parameters after which values might be returned in the form of a list, this calls for a separate class of functions returning multiple values and hence the concept of Pair and Triple was introduced in kotlin

Pair and Triple can store 2 (Pair) and 3 (Triple) values in a single instance. The comparison between two objects of these class are merely based on values

Conclusion

  1. A value or a variable must be specified for each primary constructor argument. Data class in kotlin cannot be inner, sealed, or abstract.
  2. The primary constructor's properties are the only ones that the compiler utilizes when generating functions automatically
  3. copy() function is used to duplicate an object while changing only a few of its properties while leaving the rest unaltered.
  4. In the primary constructor of the data class in kotlin default arguments can be assigned and can be changed later in the program if required
  5. Pair and Triple are standard data classes used for returning multiple values and can store 2 (Pair) and 3 (Triple) values in a single instance.