Kotlin @Serializable: Mastering Object Serialization 🎯

beginner
25 min

Kotlin @Serializable: Mastering Object Serialization 🎯

Welcome to our comprehensive guide on the @Serializable annotation in Kotlin! This tutorial is designed to help both beginners and intermediates understand the concept of object serialization with practical examples. Let's dive right in!

What is Serialization? 📝

Serialization is the process of converting an object's state into a format that can be stored or transmitted. In Kotlin, we use the @Serializable annotation to make our data classes serializable.

Why Use Serialization? 💡

  • Persistence: Serialization helps in storing objects in a file or database for later use.
  • Networking: Serialization is crucial when sending data over a network, such as between client and server.

Understanding @Serializable 📝

To make a data class serializable, we simply need to add the @Serializable annotation before the class declaration.

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

Let's break down this example:

  • data class: This is a Kotlin data class, a convenient way to create classes with equals(), hashCode(), toString(), and copy() methods.
  • @Serializable: The annotation that makes this class serializable.
  • val: Indicates that the name and age properties are read-only.

Practical Example 🎯

Let's create a simple serialization example where we serialize and deserialize a list of Person objects.

kotlin
import kotlinx.serialization.* import kotlinx.serialization.json.* @Serializable data class Person(val name: String, val age: Int) fun main() { val people = listOf( Person("John Doe", 25), Person("Jane Smith", 30) ) val json = Json { prettyPrint = true } val serializedPeople = json.serialize(people) println("Serialized People: $serializedPeople") val deserializedPeople = json.deserialize<List<Person>>(serializedPeople) println("Deserialized People: $deserializedPeople") }

In this example, we first create a Person data class and mark it as @Serializable. Then, we create a list of Person objects and serialize it to JSON using the Kotlinx Serialization library. Finally, we deserialize the JSON back to a list of Person objects.

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What is the purpose of the `@Serializable` annotation in Kotlin?

That's it for this lesson! In the next part, we'll explore how to customize object serialization in Kotlin. Stay tuned! 🚀