@Optional
- Kotlin course
- Advanced
- Lesson 28/83
- 5 min
Learn optional fields with @Optional and defaults.
What is @Optional?
@Optional is the annotation that lets a property use its default value when missing from JSON. It comes from kotlinx.serialization.
Example: @Serializable data class User(val name: String, @Optional val age: Int = 0). In this class, if age is absent from JSON it defaults to 0. This is useful for backward compatibility; when a new field is added, the previous JSON still works. In modern Kotlin a default value alone is enough; @Optional is used as an explicit marker.
Practice Default value with @Optional
Define a data class User(val name: String, @Optional val age: Int = 0) marked with @Serializable. Inside main, print println("User ready").
Starter code
// Optional annotation
// write here
import kotlinx.serialization.Serializable
import kotlinx.serialization.Optional
fun main() {
}Sample solution
@Serializable
data class User(val name: String, @Optional val age: Int = 0)
fun main() {
println("User ready")
}Expected output
User ready
Default value behavior
If a property has a default value, the class can be created even if JSON omits the field. @Optional marks this explicitly.
Example: data class User(val name: String, val age: Int = 18). The JSON {"name":"Alex"} successfully reads as User(name="Alex", age=18). With encodeDefaults = false the default value is not written to JSON. With encodeDefaults = true it is always written. This option helps keep JSON small.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is @Optional useful?
- When the JSON field is always present
- When prettyPrint is wanted
- When the class is sealed
- When a new field is added and backward compatibility is wanted Correct answer
Explanation: @Optional is useful for backward compatibility.
2 Complete the @Optional annotation name
@Serializable
data class User(val name: String, @____ val age: Int = 0)
@Serializable
data class User(val name: String, @Optional val age: Int = 0)
Explanation: @Optional marks the property as optional.
3 Match @Optional parts
| Term | Meaning |
|---|---|
@Optional |
Optional marker |
default value |
Used for missing field |
encodeDefaults |
Writing option |
JSON |
Data format |