Data Classes
Slumber serializes data classes by reflecting on the primary constructor. No annotations needed for standard cases.
Basic data classes
Every constructor parameter becomes a field in the serialized output:
data class User(val name: String, val age: Int)
val codec = Codec.default
codec.slumber(User("Alice", 30))
// → { "name": "Alice", "age": 30 }
codec.awake<User>(mapOf("name" to "Bob", "age" to 25))
// → User(name="Bob", age=25) Nested data classes
Nesting works recursively — no depth limit:
data class Address(val city: String, val zip: String)
data class Company(val name: String, val hq: Address)
data class Employee(val name: String, val company: Company)
val emp = Employee("Alice", Company("ACME", Address("Berlin", "10115")))
codec.slumber(emp)
// → {
// "name": "Alice",
// "company": {
// "name": "ACME",
// "hq": { "city": "Berlin", "zip": "10115" }
// }
// } Enums
Enums serialize to their name as a string:
enum class Role { ADMIN, USER, GUEST }
data class Account(val name: String, val role: Role)
codec.slumber(Account("Alice", Role.ADMIN))
// → { "name": "Alice", "role": "ADMIN" }
codec.awake<Account>(mapOf("name" to "Bob", "role" to "USER"))
// → Account(name="Bob", role=Role.USER) Kotlin object singletons
Kotlin object singletons are preserved — the same instance is returned on deserialization:
object AppConfig {
val version = "1.0"
}
val data = codec.slumber(AppConfig)
// → {} (empty map)
val restored = codec.awake<AppConfig>(data)
// restored === AppConfig (same instance) Computed fields with @Slumber.Field
By default, only constructor parameters are serialized. To include computed properties, use @Slumber.Field:
data class Invoice(val items: List<Double>, val taxRate: Double) {
@Slumber.Field
val subtotal get() = items.sum()
@Slumber.Field
val tax get() = subtotal * taxRate
@Slumber.Field
val total get() = subtotal + tax
}
codec.slumber(Invoice(listOf(10.0, 20.0, 30.0), 0.19))
// → {
// "items": [10.0, 20.0, 30.0],
// "taxRate": 0.19,
// "subtotal": 60.0,
// "tax": 11.4,
// "total": 71.4
// } @Slumber.Field works on properties, getters, and lazy fields. Only serialization is affected — deserialization still uses the constructor.
Private constructors
Data classes with private constructors still work — Slumber uses Kotlin reflection to access them:
data class UserId private constructor(val value: String) {
companion object {
fun of(raw: String) = UserId(raw.trim().lowercase())
}
}
// Deserialization bypasses the companion factory
codec.awake<UserId>(mapOf("value" to "ABC-123"))
// → UserId(value="ABC-123") Generic data classes
Full generic support — type parameters are preserved through serialization:
data class Wrapper<T>(val value: T)
data class Pair<A, B>(val first: A, val second: B)
codec.awake<Wrapper<Int>>(mapOf("value" to 42))
// → Wrapper(value=42)
codec.awake<Pair<String, Int>>(mapOf("first" to "hello", "second" to 99))
// → Pair(first="hello", second=99)