Search⌘ K
AI Features

Data Models

Explore how to define data classes in Kotlin to efficiently hold and manage data in Android apps. Understand the automatically generated methods such as toString, equals, and copy. Discover how to implement Serializable and Parcelable interfaces for passing objects between activities, improving app performance and data handling.

Data classes

Data classes are used to hold data. They’re marked with the data keyword to tell the compiler that we’re creating this class to hold data so that it can automatically create the necessary functions to handle and process data.

Kotlin
data class User(val name:String, val age:Int)

A data class contains state and fields. For a class to be considered a data class, the following must be true:

  • The primary constructor should have at least one parameter.
  • Each parameter must indicate if it’s a val or var.
  • Data classes cannot be abstract, sealed, open, or inner. They can extend other classes.

The data class methods

The data class has methods that are automatically generated when the compiler notices the class is meant to hold data and to keep our code concise. We don’t need ...