@Serializable
- Kotlin course
- Advanced
- Lesson 25/83
- 5 min
Learn class serialization with @Serializable.
The @Serializable annotation
@Serializable is the annotation that lets a Kotlin class be converted to formats like JSON. It comes from the kotlinx.serialization library.
You add @Serializable to a data class; the compiler generates a serializer automatically. Example: @Serializable data class User(val name: String, val age: Int). This class can be turned to and from JSON easily. Properties should be val; mutable properties may cause issues during serialization. All properties must have serializable types.
Using @Serializable
To add @Serializable to a class you put @Serializable above it and import kotlinx.serialization.Serializable.
Example: @Serializable data class Product(val name: String, val price: Double). This class can now be turned into JSON. Json.encodeToString(product) returns a JSON string. Json.decodeFromString<Product>(json) turns a JSON string into a Product. All of this is type safe at compile time.
Practice Define a Serializable User
Define a data class User(val name: String) marked with @Serializable. Inside main, set val user = User("Alex") and print println("Hello, ${user.name}!").
Starter code
// Serializable annotation
// write here
import kotlinx.serialization.Serializable
fun main() {
}Sample solution
@Serializable
data class User(val name: String)
fun main() {
val user = User("Alex")
println("Hello, ${user.name}!")
}Expected output
Hello, Alex!
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the role of the @Serializable annotation?
- Makes the class serializable Correct answer
- Makes the class final
- Makes the class thread safe
- Makes the class singleton
Explanation: @Serializable makes a class serializable.
2 Complete the annotation name
@____
data class User(val name: String)
@Serializable
data class User(val name: String)
Explanation: @Serializable marks the class.
3 Match Serializable parts
| Term | Meaning |
|---|---|
@Serializable |
Marks the class |
data class |
Data class |
val |
Immutable property |
kotlinx.serialization |
Library |