0
0
KotlinHow-ToBeginner · 3 min read

How to Create Data Class in Kotlin: Syntax and Examples

In Kotlin, you create a data class using the data class keyword followed by the class name and its properties inside parentheses. This automatically provides useful functions like toString(), equals(), and copy() for the class.
📐

Syntax

A Kotlin data class is declared with the data class keyword, followed by the class name and a primary constructor with properties.

  • data class: keyword to create a data class
  • ClassName: the name of your data class
  • Properties: variables inside parentheses that define the data held

Example syntax:

kotlin
data class ClassName(val property1: Type1, val property2: Type2)
💻

Example

This example shows a data class Person with two properties: name and age. It demonstrates how to create an instance and use the toString() and copy() functions automatically provided.

kotlin
data class Person(val name: String, val age: Int)

fun main() {
    val person1 = Person("Alice", 30)
    println(person1)  // Uses toString()

    val person2 = person1.copy(age = 31)  // Creates a new object with changed age
    println(person2)
}
Output
Person(name=Alice, age=30) Person(name=Alice, age=31)
⚠️

Common Pitfalls

Common mistakes when creating data classes include:

  • Not using val or var for properties in the primary constructor, which means they won't become class properties.
  • Trying to create a data class without any properties, which is not allowed.
  • Using mutable properties (var) carelessly, which can cause unexpected behavior.

Example of wrong and right ways:

kotlin
// Wrong: properties missing val/var
// data class WrongPerson(name: String, age: Int) // This will cause a compiler error

// Right:
data class RightPerson(val name: String, val age: Int)
📊

Quick Reference

FeatureDescription
data classCreates a class with useful methods like toString(), equals(), hashCode(), and copy()
Primary constructorDefines properties with val or var inside parentheses
copy()Creates a new instance copying existing values with optional changes
equals()Checks if two instances have the same property values
toString()Returns a readable string of the object’s properties

Key Takeaways

Use the 'data class' keyword followed by class name and properties with val or var.
Data classes automatically provide useful functions like toString(), equals(), and copy().
Always declare properties in the primary constructor with val or var to make them part of the class.
Data classes must have at least one property in the primary constructor.
Use copy() to create modified copies of data class instances easily.