CodeBlanks Logo Icon CodeBlanks

data class

Learn to define data classes with data class.

data class

A data class is a special class designed to hold data. With the data modifier Kotlin generates equals, hashCode, toString, copy and componentN methods automatically.

Example: data class User(val name: String, val age: Int). This single line carries two properties and five helper methods. Data classes must have a primary constructor with at least one parameter. Parameters marked val or var become properties.

data class constraints

The primary constructor of a data class must have at least one parameter. All parameters must be marked val or var; otherwise they do not become properties.

Example: data class User(val name: String, val age: Int) is valid. data class User(name: String) lacks properties, so equals and toString do not work as expected. Data classes cannot be open, abstract or sealed; inheritance is closed.

Practice Define the User data class

Define a data class named User with a primary constructor taking val name: String, val age: Int. In main create a User("Alex", 30) instance and print it with println.

Starter code

Main.kt
// Define the User data class
// with name and age properties
// instantiate and print in main

Sample solution

Main.kt
data class User(val name: String, val age: Int)

fun main() {
    val u = User("Alex", 30)
    println(u)
}

Expected output

User(name=Alex, age=30)

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does <code>data class User(val name: String)</code> generate automatically?

  • Only a constructor
  • equals, hashCode, toString and copy Correct answer
  • Only toString
  • Nothing

Explanation: A data class generates equals, hashCode, toString, copy and componentN.

2 Complete the data class definition

Question
data ____ User(val name: String, val age: Int)
Answer
data class User(val name: String, val age: Int)

Explanation: data class declares a data class.

3 Match the data class methods

Term Meaning
equals Content comparison
hashCode Hash value
toString Readable string
copy Clone production

All lessons in Intermediate