Back to Blog

Kotlin with Copilot: Create a data class with name and age

Sandy LaneSandy Lane

Video: Kotlin with Copilot: Create a data class with name and age by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin with Copilot: Create a Data Class with Name and Age

This example demonstrates how to define a simple Kotlin data class to hold a person's name and age. It also shows how to create a function that prints the details of an instance of this data class.

Code

// Define a data class with two properties: name and age
data class Person(val name: String, val age: Int)

// Function to print the details of a Person object
fun printPersonInfo(person: Person) {
  println("Name: ${person.name}, Age: ${person.age}")
}

fun main() {
  // Create an instance of Person
  val person = Person("Alice", 30)
  // Print the person's information
  printPersonInfo(person)
}

Key Points

  • Data classes in Kotlin automatically generate useful methods like toString(), equals(), and copy().
  • Properties are declared in the primary constructor for concise syntax.
  • Functions can accept data class instances to access and display their data.
  • Kotlin string templates allow embedding variables directly within strings for easy output.