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!
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.
@Serializable 📝To make a data class serializable, we simply need to add the @Serializable annotation before the class declaration.
@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.Let's create a simple serialization example where we serialize and deserialize a list of Person objects.
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.
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! 🚀