CodeGym /Courses /Kotlin SELF /Serialization of enum and sealed class: discriminator and...

Serialization of enum and sealed class: discriminator and Ok/Error

Kotlin SELF
Level 48, Lesson 2
Available

1. enum: values in JSON and @SerialName

When you write a program, you constantly need to represent “one of several”. For example: an operation status (success/error), an expense category (food/transport), a command type ("add"/"list"/"remove"), or an order state. The naive approach is to store it as strings like "ok" or "food". It works right up until the moment you make a typo ("foood"), and the program happily continues living—just in a parallel universe.

enum and sealed class are ways to tell the compiler: “look, there are only a few options, and there cannot be any others”. In Kotlin this is especially nice because a when over an enum or a sealed class can be exhaustive: if you forget to handle a case, the compiler (in expression mode) will start complaining and save you from a bug. That behavior—“the options are finite”—is something you also want to preserve in the JSON contract.

What an enum looks like in JSON by default

enum is essentially a “dictionary of allowed values”. In Kotlin, enum class also gives you handy things like name, ordinal, entries, valueOf(...), and so on. But today we care about the main thing: how enum turns into JSON.

By default, kotlinx.serialization serializes an enum as a string containing the constant name. That is, FOOD becomes "FOOD". It is simple, readable, and often sufficient, but there is a subtle problem: the constant name is a name in code, while JSON is an external format. Sometimes the external format requires different values (for example, "food" instead of "FOOD"), and sometimes you want to safely rename a constant in code without breaking old files.

Let’s make a mini example based on a learning console app for “expense tracking”. One expense model and a category as an enum.

import kotlinx.serialization.Serializable

@Serializable
enum class ExpenseCategory {
    FOOD, TRANSPORT, ENTERTAINMENT
}

Now serialization:

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

fun main() {
    val json = Json { prettyPrint = true }

    println(json.encodeToString(ExpenseCategory.FOOD))
    // "FOOD"
}

Key idea: JSON contains the enum constant name. And if tomorrow you rename ENTERTAINMENT to FUN (because you want it shorter), then old JSON files containing "ENTERTAINMENT" will stop being read as before.

Stable values with @SerialName

At this point, a very human desire typically appears: “let’s never rename enums”. It is like the promise “I will never eat sweets”. Formally possible, psychologically questionable.

It is better to separate the “internal name in code” from the “external name in the format”. For that, you can put @SerialName on enum values. Then you can name the constant in code however you like, while storing in JSON what you agreed on in the format.

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
enum class ExpenseCategory {
    @SerialName("food")
    FOOD,

    @SerialName("transport")
    TRANSPORT,

    @SerialName("entertainment")
    ENTERTAINMENT
}

Let’s verify serialization:

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

fun main() {
    val json = Json { prettyPrint = false }

    println(json.encodeToString(ExpenseCategory.TRANSPORT))
    // "transport"
}

Now the JSON is more “human-friendly” (or “API-like”) and, more importantly, more stable: you can rename ENTERTAINMENT to FUN in Kotlin code but keep @SerialName("entertainment"), and the format will not suffer.

2. sealed class: discriminator and @SerialName

Why JSON needs a discriminator

If an enum is “one of N values”, then a sealed class is “one of N types”. And each type can carry its own data. It is like a surprise box, but an honest one: there are only a few surprises, all known in advance, and the compiler keeps them on a list.

A classic example: an operation result. Success carries useful data (for example, the id of the created expense), while failure carries an error message.

import kotlinx.serialization.Serializable

@Serializable
sealed class OpResult {
    @Serializable
    data class Ok(val id: Int) : OpResult()

    @Serializable
    data class Error(val message: String) : OpResult()
}

And then a question arises: how do you store this in JSON?

If we write just the fields, we lose the most important thing: when we read JSON back, how do we know whether it is Ok or Error? JSON has no built-in concept of a “sealed class variant”. It just sees an object { ... }.

That is why polymorphic serialization (and sealed is polymorphism “in miniature”) needs a special service field: the type discriminator. This field says: “the variant is this one”.

Typical shape:

{ "type": "ok", "id": 10 }

or

{ "type": "error", "message": "Invalid input" }

Then, when reading JSON, the library looks at "type" and decides which subtype to create.

classDiscriminator in Json { ... }

It is important that the discriminator has a stable name and does not conflict with your regular fields. The most popular option is "type", but in some domains the word type is already taken by business meaning (“product type”, “operation type”). Then it is better to choose another name, for example "kind" or "resultType".

In kotlinx.serialization, the discriminator field name is configured via classDiscriminator.

import kotlinx.serialization.json.Json

val json = Json {
    prettyPrint = true
    classDiscriminator = "type"
}

A small real-life detail: the setting must be the same where you write JSON and where you read JSON. If you saved a file with "type" and later read it using Json { classDiscriminator = "kind" }, the library will look in the wrong place and “won’t recognize” the variants.

@SerialName on variants: pinning ok/error

Right now our variants are named Ok and Error. If we serialize them “as is”, the external format may start depending on class and package names (and you can absolutely refactor packages). Also, in JSON you want to see short, clear markers: "ok" and "error".

Here @SerialName helps again, but now we apply it not to a field and not to an enum value, but to a sealed subclass.

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
sealed class OpResult {

    @Serializable
    @SerialName("ok")
    data class Ok(val id: Int) : OpResult()

    @Serializable
    @SerialName("error")
    data class Error(val message: String) : OpResult()
}

Now we explicitly lock in the Ok/Error convention as a format contract, not as “whatever we happened to name the classes”.

Let’s verify serialization:

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

fun main() {
    val json = Json {
        prettyPrint = true
        classDiscriminator = "type"
    }

    val r: OpResult = OpResult.Ok(id = 10)
    println(json.encodeToString(r))
    /*
    {
        "type": "ok",
        "id": 10
    }
    */
}

Notice a small but important thing: the variable r has type OpResult, not OpResult.Ok. And this is not just “pretty”—it affects the JSON.

Nuance: the discriminator appears when serializing through the base type

This is the moment where students most often run into “why doesn’t it work?” and “why is the JSON different?”. The reason is the static type of the expression in Kotlin.

If you serialize the object as the concrete type OpResult.Ok, the library assumes “the type is already known”, so a discriminator may not be needed. But if you serialize as OpResult, you need a discriminator because there are multiple variants.

Compare:

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

fun main() {
    val json = Json { classDiscriminator = "type" }

    val asChild = OpResult.Ok(id = 10)
    val asBase: OpResult = OpResult.Ok(id = 10)

    println(json.encodeToString(asChild)) // {"id":10}
    println(json.encodeToString(asBase))  // {"type":"ok","id":10}
}

Technically both JSON outputs are valid, but the second one can be restored unambiguously because it contains "type". The first one cannot be restored as OpResult without additional information: { "id": 10 } could be anything (and even more so, it could become anything after the model is extended).

Practical rule: if you are designing a JSON format for a sealed class and want reliable decodeFromString<OpResult>(...), serialize the result through the base type (or explicitly specify the type parameter).

3. Decoding and handling via when

Now let’s do the reverse operation: from JSON back into a Kotlin object. Here you will feel why we need the discriminator: it is exactly what allows the library to choose the variant.

import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json

fun main() {
    val json = Json { classDiscriminator = "type" }

    val s1 = """{"type":"ok","id":10}"""
    val s2 = """{"type":"error","message":"Bad input"}"""

    val r1 = json.decodeFromString<OpResult>(s1)
    val r2 = json.decodeFromString<OpResult>(s2)

    println(r1) // Ok(id=10)
    println(r2) // Error(message=Bad input)
}

Next—classic Kotlin: process the result with an exhaustive when. With a sealed class this is especially nice because Kotlin knows all variants and can require you to handle them all.

fun toHumanText(r: OpResult): String = when (r) {
    is OpResult.Ok -> "Success: created id=${r.id}"
    is OpResult.Error -> "Error: ${r.message}"
}

This when is good because you do not use null, you do not use Boolean flags like isOk, and you do not make “magic” strings. You have a strict result model, and the compiler helps you not forget to handle a case.

4. Mini diagram of encode/decode for sealed

To internalize “why type appears there”, it helps to look at the process as a small pipeline.

flowchart TD
    A["Kotlin: OpResult (sealed)"] -->|encodeToString| B["JSON object"]
    B --> C["discriminator field: type"]
    C --> D["value: ok / error"]
    B -->|decodeFromString⟨OpResult⟩| E["Kotlin: OpResult.Ok or OpResult.Error"]
    E -->|when| F["human-readable text / further logic"]

If at the JSON stage you do not have type, then the path “back” into OpResult becomes either impossible or turns into guessing based on the object internals (which is usually very fragile).

5. Example in expense tracking: command results as Ok/Error

Now we’ll take a step that feels small but in practice makes the program more mature: we will stop returning “error strings” and start returning a strict Ok/Error result. And then (if we want) we can serialize that result to JSON—for example, for logs, export, or tests.

Let’s add minimal application models:

import kotlinx.serialization.Serializable

@Serializable
data class Expense(
    val id: Int,
    val title: String,
    val amount: Int,
    val category: ExpenseCategory
)

And a service that adds an expense and returns OpResult. The logic is intentionally simple, without future architectural “layers”—we are still learning to keep code understandable.

class ExpenseService {
    private val items = mutableListOf<Expense>()
    private var nextId = 1

    fun add(title: String, amount: Int, category: ExpenseCategory): OpResult {
        if (title.isBlank()) return OpResult.Error("Title must not be blank")
        if (amount <= 0) return OpResult.Error("Amount must be > 0")

        val e = Expense(id = nextId++, title = title, amount = amount, category = category)
        items.add(e)
        return OpResult.Ok(id = e.id)
    }
}

Notice how nice it reads: the function returns not a Boolean, not an Int where “-1 means error”, and not a String? (where null means success and a string means error). It returns a clear domain result.

Now in main we can do a demo and also show result serialization:

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

fun main() {
    val service = ExpenseService()

    val json = Json {
        prettyPrint = true
        classDiscriminator = "type"
    }

    val r: OpResult = service.add("Coffee", 250, ExpenseCategory.FOOD)
    println(toHumanText(r))                  // Success: created id=1
    println(json.encodeToString(r))
}

If you ask now: “why would I serialize OpResult if I’m just printing it?”, the answer is: today this is a learning example, but in real life such results often go either to a file (log), to the network (API), or to test “golden files”. And that is where the discipline of Ok/Error and stable variant names really pays off.

6. Common mistakes when serializing enum and sealed class

Mistake #1: store an enum in JSON as the constant name and then freely rename it in code.
The problem is not that you can’t rename it; the problem is that you silently change the external format. Today you have "FOOD", tomorrow "MEAL", and old files turn into a museum of errors. The fix is simple: pin external values using @SerialName on enum values, and rename Kotlin names as much as you want (within reason).

Mistake #2: expect a sealed class to be restored from JSON without a type field.
JSON does not store “subtype information” by itself. If you did not add a discriminator, decodeFromString<OpResult>(...) will not be able to tell which subtype to create. The discriminator is not “extra bureaucracy”, it is the minimum price for unambiguity.

Mistake #3: choose a discriminator name that conflicts with a business field.
If you set classDiscriminator = "type", and later add a field val type: String for business purposes, you will throw a conflict party. It is better to reserve a name for the discriminator in advance (for example, "type" or "kind") and not use it in regular data, or choose a less conflict-prone name.

Mistake #4: serialize a sealed variant as a concrete subtype and be surprised there is no discriminator.
If you serialize OpResult.Ok(...) as OpResult.Ok, the JSON may omit "type". Then you try to read it as OpResult—and that’s it. If you design an external format, serialize through the base type (or explicitly pass the type parameter via encodeToString<OpResult>(...)) so the discriminator is always present.

Mistake #5: create a “zoo” of result variants instead of a stable Ok/Error pair.
It is tempting to have Success/Failure, then somewhere Ok/Error, then Fine/Bad. The result is that code and format drift apart. For a learning project and for most practical operations, it is useful to keep a single result template: Ok for success and Error for failure. It makes when handling consistent everywhere and reduces the number of “special cases” you have to keep in your head.

1
Task
Kotlin SELF, level 48, lesson 2
Locked
Expense with a category
Expense with a category
1
Task
Kotlin SELF, level 48, lesson 2
Locked
Operation result
Operation result
1
Task
Kotlin SELF, level 48, lesson 2
Locked
Result message
Result message
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION