Kotlin Data Classes Tutorial šŸŽÆ

beginner
22 min

Kotlin Data Classes Tutorial šŸŽÆ

Welcome to our deep dive into Kotlin's Data Classes! In this lesson, we'll explore this powerful feature that makes your coding life easier, especially when dealing with complex data structures. Let's get started!

What are Data Classes? šŸ“

Data Classes are a concise way to create classes that come with pre-built methods, like toString(), equals(), and hashCode(). They are perfect for representing simple data structures like objects or records.

Creating a Data Class šŸ’”

To create a Data Class, simply add the data keyword before the class keyword when defining a class. Here's a simple example of a Person data class:

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

šŸ’” Pro Tip: Use val for immutable properties and var for mutable properties.

Using a Data Class āœ…

Now, let's see how to create an instance of our Person data class and use it in your code:

kotlin
val john = Person("John Doe", 30, "New York") println(john) // Output: Person(name=John Doe, age=30, city=New York)

Data Classes and Properties šŸ“

Each property in a data class has:

  1. A getter (getName(), getAge(), getCity())
  2. A setter (setName(), setAge(), setCity()) that are marked as private
  3. A toString() method that gives a string representation of the object
  4. Equality functions (equals(), hashCode()) to compare instances

Advanced Data Class Features šŸ’”

Data classes can also:

  1. Define primary constructors, which are used to initialize properties.
  2. Have constructors with named arguments, which makes the constructor more readable and flexible.
  3. Declare secondary constructors, which can call the primary constructor to initialize properties.

Practical Example šŸŽÆ

Let's create a Product data class with named arguments and a secondary constructor:

kotlin
data class Product( val id: Int, val name: String, val price: Double, val brand: String ) { constructor(name: String, price: Double, brand: String) : this(0, name, price, brand) } val product1 = Product("Apple", 1.5, "Apple Inc.") val product2 = Product(id = 1, name = "Banana", price = 0.5, brand = "Dole")

Quiz šŸ“

Quick Quiz
Question 1 of 1

What is a Data Class in Kotlin?


And that's it for our Kotlin Data Classes tutorial! We hope you found this lesson useful and practical. As always, happy coding! 😊