CodeGym /Courses /Kotlin SELF /Cyclic references

Cyclic references

Kotlin SELF
Level 48, Lesson 4
Available

1. Introduction

When you move from simple structures (numbers, strings, lists) to “real” objects, you start linking data to each other. That’s natural: an expense has a category, a category has a list of expenses, a user has a manager, and a manager… also has a manager (sometimes it’s the same person, but HR would rather you didn’t mention that).

From Kotlin’s perspective, classes and objects exist precisely to keep data and behavior together, and to create instances that can reference each other. This is the basic object-oriented model: “an object stores fields; fields can be references to other objects.”

The problem doesn’t show up when you create references; it shows up when you want to serialize this state: turn it into text (JSON) so that it can be restored later.

2. Why JSON “isn’t about cycles”: tree vs. graph

Without academic pathos: by its nature, JSON is a tree. In a tree, each node has “children” (nested objects/arrays), and if you keep going “down,” you’re guaranteed to eventually hit a leaf (string/number/boolean/null) and stop.

Cyclic references are already a graph. In a graph, you can follow arrows forever: you leave A, arrive at B, then at C, and then back at A — hello, infinity.

Let’s look at a picture:

flowchart TD
    subgraph JSON_как_дерево
      A1["Root"] --> B1["Child 1"]
      A1 --> C1["Child 2"]
      B1 --> D1["leaf: 123"]
      C1 --> E1["leaf: \"text\""]
    end

    subgraph Объекты_как_граф_с_циклом
      A2["A"] --> B2["B"]
      B2 --> C2["C"]
      C2 --> A2
    end

JSON has no built-in mechanism for “a reference to a previously encountered object.” It can’t say: “and here this is not a new object, but the very same one that appeared above.” So trying to serialize a graph as a tree usually turns into an attempt to “unroll” the cycle into infinite nesting.

3. A mini example of a cycle in Kotlin: “Alice manages Bob, Bob manages Alice”

First, let’s make a tiny model so it’s clear that a cycle isn’t something rare or mystical, but literally just two references.

class User(val id: Int, val name: String) {
    var manager: User? = null
}

fun main() {
    val alice = User(1, "Alice")
    val bob = User(2, "Bob")

    alice.manager = bob
    bob.manager = alice // cycle

    println(alice.manager?.name) // Bob
    println(bob.manager?.name)   // Alice
}

In memory, this works perfectly: Kotlin objects can safely hold references to each other; the GC (JVM garbage collector) doesn’t faint because of it. And then the classic thought appears: “Well, if it works, let’s add @Serializable and save it to JSON.”

4. What happens with naive serialization

When a serializer converts an object to JSON, it follows roughly this logic: write the object’s fields → if a field is an object, serialize it → inside it, fields again → and so on. This is often implemented via recursion.

If there’s a cycle inside, serialization starts “unrolling” it over and over. In practice this usually ends with a stack overflow (often it looks like StackOverflowError) or another error depending on the particular implementation and settings. The core idea is the same: “infinite nesting doesn’t fit into finite memory.”

A pseudo example (note: don’t do this; it’s a demonstration of the problem):

import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

@Serializable
data class UserDto(
    val id: Int,
    val name: String,
    val manager: UserDto? = null,
)

fun main() {
    val alice = UserDto(1, "Alice")
    // In practice, it’s awkward to create a cycle here because a data class is immutable,
    // but the point of the problem is exactly the cycle of references.
    println(Json.encodeToString(alice))
}

And here’s the important practical conclusion: it’s impossible to “magically” store a cyclic graph in plain JSON as nesting. You need to change the data representation for storage.

5. Why this isn’t a “library bug”: format limitations, not Kotlin

It’s very tempting to say: “Well, the library is bad; they should fix it.” But the problem is deeper: JSON as a format does not store “object identity” and “references.”

When you write Kotlin code, two fields can reference the same object. But in JSON you write values; that is, you literally print text. Text has no notion of “this is the same object as 20 lines above.”

If a serializer tried to solve this on its own, it would have to:

  1. introduce service identifiers for objects in JSON,
  2. introduce references like {"$ref": "id-123"},
  3. agree on a format for those references,
  4. be able to restore the graph when reading.

That is, it would effectively invent a new format on top of JSON. Sometimes that’s done in complex systems, but in a learning course we choose a more honest and practical approach: we design the storage model ourselves.

6. The “id instead of reference” strategy: the main trick against cycles

The most reliable and common strategy sounds boring, but it saves your nerves: instead of storing a nested object, we store its identifier.

That is, not manager: User, but managerId: Int?.

Not category: Category, but categoryId: Int.

And we store the objects themselves (their “table”) separately: as a list or a Map by id. Essentially, we make a mini version of how relationships work in a database: data separate, links separate.

And this fits perfectly into our learning console project (let’s условno call it BudgetBuddy): we store expenses and categories, print reports, and now we want to save all this to JSON so that it can be read back without pain.

7. A cycle in “expenses ↔ categories”: why it appears

Imagine we want a “nice-looking” in-memory model.

A category knows its expenses because that’s convenient for building reports like “show all expenses for the category.” An expense knows its category because that’s convenient for printing a line like “2026‑01‑14: coffee, category Food.”

That results in a bidirectional relationship:

flowchart LR
    C["Category"] -->|expenses| E["Expense"]
    E -->|category| C

Code (this demonstrates how the cycle arises):

class Category(val id: Int, val title: String) {
    val expenses: MutableList<Expense> = mutableListOf()
}

class Expense(val id: Int, val title: String, val amountCents: Long) {
    lateinit var category: Category
}

Inside the app, this is convenient, but for serialization it’s a trap: if we try to write Category, the serializer will go into expenses, there is Expense, inside it there is category, and inside category there is expenses again… and off we go.

8. “Storage model” vs. “working model”

Right now we don’t need to dive into complex architecture. One simple rule is enough: what is convenient in memory does not have to be what is convenient to store in JSON.

Let’s make two models:

  • Category and Expense — for working in the app (can include references).
  • CategoryStored and ExpenseStored — for JSON, only primitives and id references.

Minimal “stored” models:

import kotlinx.serialization.Serializable

@Serializable
data class CategoryStored(
    val id: Int,
    val title: String,
)

@Serializable
data class ExpenseStored(
    val id: Int,
    val title: String,
    val amountCents: Long,
    val categoryId: Int,
)

Notice: there is no object nesting here, only numbers and strings. JSON will be as calm as a cat after lunch.

9. A JSON container: an application state “dump”

If you store a “category table” and an “expense table,” it’s convenient to put them into one root object that will be saved to a file.

import kotlinx.serialization.Serializable

@Serializable
data class BudgetDump(
    val categories: List<CategoryStored>,
    val expenses: List<ExpenseStored>,
)

Why this is nice:

  • JSON has a single root (as is usually expected),
  • we can clearly see which collections we store,
  • adding new sections later is easier (for example, app settings) without immediately breaking the format.

10. Example serialization without cycles

Now the code that creates a “dump” and serializes it.

import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

fun main() {
    val dump = BudgetDump(
        categories = listOf(CategoryStored(1, "Food")),
        expenses = listOf(ExpenseStored(10, "Coffee", 350, categoryId = 1)),
    )

    val json = Json { prettyPrint = true }
    println(json.encodeToString(dump))
    // Prints JSON with categories and expenses, without recursion
}

And this is the key point: we don’t “fix” the serializer; we make the data serializable.

11. How to restore links when reading: rebuilding the graph

Saving it “flat” is only half the job. The other half (yes, exactly like that) is: after decodeFromString, bring back convenient in-memory references.

The assembly idea is simple:

  1. read BudgetDump,
  2. create categories and put them into a Map<Int, Category> by id,
  3. create expenses; for each one find its category by categoryId,
  4. set references and populate the category’s expense list.

Code skeleton (not huge, but illustrative):

fun buildState(dump: BudgetDump): List<Category> {
    val categoriesById = dump.categories.associate { it.id to Category(it.id, it.title) }

    for (e in dump.expenses) {
        val category = categoriesById.getValue(e.categoryId)
        val expense = Expense(e.id, e.title, e.amountCents).also { it.category = category }
        category.expenses.add(expense)
    }

    return categoriesById.values.toList()
}

Here we use getValue(...) because in a valid dump the category must exist. If it doesn’t, the dump is corrupted or old, and that’s a separate topic of error handling (we won’t go deep today, but at least we understand where it “can blow up”).

12. Useful nuances

“Stable id” is your mini data contract

For the “id instead of reference” strategy to work, identifiers must be stable and unique.

That is: if you once saved the Food category with id = 1, and then on the next run you created a new Food category again with id = 1, that’s fine. But if you accidentally assign id = 1 to a different category, then expenses will “move” into someone else’s category and you’ll get accounting horror.

In learning apps, people often implement a simple id generator: “max id + 1”. It’s not ideal for large systems, but for a console project it’s a reasonable discipline.

An alternative to bidirectional links: a one-way model

Sometimes it’s проще not to assemble the “full graph,” but to keep the model one-way. That is, Expense stores categoryId, and Category does not store the expense list. When you need to show a category’s expenses, you filter the expense list.

It looks a bit less “object-y,” but serialization becomes almost trivial, and post-read assembly is not needed.

A small illustration with collections:

fun expensesForCategory(expenses: List<ExpenseStored>, categoryId: Int): List<ExpenseStored> {
    return expenses.filter { it.categoryId == categoryId }
}

This approach often turns out to be even more useful than “references in all directions,” especially while the project is small: less mutability, less risk of getting out of sync.

Where @Transient fits: keeping “cache” out of JSON

Sometimes you want to store in an object “both references and id, and an expense list, and also a flag ‘already computed’.” But the JSON format should remain clean.

If you have a computed or cached field that should not leak into JSON, you already know the tool: @Transient (with a default). We won’t go deeper (that was the previous lecture’s topic), but let’s lock in the key idea: JSON contains the contract, not your internal convenience.

Cheat-sheet diagram: “id instead of reference”

flowchart TD
    subgraph InMemory["V pamyati (udobno rabotat’)"]
        C1["Category(id=1)"] --> E1["Expense(id=10)"]
        E1 --> C1
    end

    subgraph Stored["V JSON (udobno khranit’)"]
        CS["CategoryStored(id=1)"]
        ES["ExpenseStored(id=10, categoryId=1)"]
    end

    Stored -->|"buildState()"| InMemory

Saving goes from memory to Stored (usually via mapping), and loading goes back via assembly.

13. Typical mistakes when working with cyclic references

Mistake #1: trying to “just serialize an object with references” and expecting the library to figure it out.
Almost always this ends in infinite recursion: the serializer honestly walks fields, and the cycle prevents it from stopping. In such situations, you should not “break JSON,” but change the data representation: store id instead of a nested object.

Mistake #2: keeping both manager: User and managerId: Int at the same time, but without a clear rule of “which one is the source of truth.”
It’s easy to get out of sync: managerId = 2, but manager for some reason points to user 3. If you do use both fields (for example, one for storage and the other for convenience), you need a clear rule: what gets serialized, how the graph is built, and when it gets updated.

Mistake #3: forgetting about identifier stability.
The “id instead of reference” strategy works only if id values are unique and not accidentally reused. Otherwise, links will be restored incorrectly, but the program might not even crash — it will just start “lying” to the user, which is the worst kind of bugs.

Mistake #4: serializing internal caches and derived data.
For example, storing an expense list on the category, even though it can be restored from expenses by categoryId. In JSON this creates duplication and a risk of divergence. Usually it’s better to store primary data and restore derived data on load, and keep temporary fields out of the format.

Mistake #5: not thinking through what to do with “no relationship.”
If a relationship can be missing (for example, a user has no manager), it must be explicitly expressed in the storage model: managerId: Int?. Trying to “stuff” the absence of a relationship into 0 or -1 often leads to weird edge cases and extra checks.

Mistake #6: trying to fix cycles with a custom serializer without changing the model.
A custom serializer is great when the value format needs to be unusual (for example, Money as a string). But cycles are a data-structure problem: graph vs. tree. Usually this is solved by designing the storage model, not by fancy tricks at the KSerializer<T> level.

1
Task
Kotlin SELF, level 48, lesson 4
Locked
User without nesting
User without nesting
1
Task
Kotlin SELF, level 48, lesson 4
Locked
Flat storage
Flat storage
1
Task
Kotlin SELF, level 48, lesson 4
Locked
Budget dump
Budget dump
1
Task
Kotlin SELF, level 48, lesson 4
Locked
Building the state
Building the state
1
Survey/quiz
Serialization, level 48, lesson 4
Unavailable
Serialization
Serialization
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION