Skip to content
Learn Netverks

Lesson

Step 17/36 47% through track

sealed-classes

Sealed classes

Last reviewed Jun 1, 2026 Content v20260601
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Sealed classes: the syntax, patterns, and safety habits you need before advancing in Kotlin.

Sealed classes model restricted hierarchies—exhaustive when expressions catch API drift at compile time.

You will apply Sealed classes in contexts like: Android apps, Spring services, and shared KMP modules.

Write Kotlin in main.kt with fun main(), click Run on server—the dev runner kotlinc compiles to a JVM jar and java runs it; use println for output (requires JDK + kotlinc; LEARNING_RUNNER_ENABLED=true).

When you can explain the previous lesson's ideas without copying starter code.

Sealed classes restrict inheritance to a known set of subclasses in the same module—ideal for modeling closed hierarchies like UI states or network results, similar in spirit to C# discriminated unions with when exhaustiveness.

Sealed hierarchy

sealed class Result {
    data class Ok(val value: String) : Result()
    data class Err(val message: String) : Result()
}

fun describe(r: Result) = when (r) {
    is Result.Ok -> "OK: ${r.value}"
    is Result.Err -> "ERR: ${r.message}"
}

Subclasses must be direct—nested classes, objects, or data classes in the same file or module per visibility rules.

Important interview questions and answers

  1. Q: Sealed vs enum?
    A: Enums are fixed constant sets with one instance each; sealed classes carry distinct data per subtype.
  2. Q: Why sealed with when?
    A: Compiler can verify exhaustive when branches when all subclasses are known.

Self-check

  1. What control flow pairs well with sealed types?
  2. Can sealed subclasses live anywhere in the project?

Tip: Pair sealed hierarchies with exhaustive when—great for UI state and API result modeling.

Interview prep

Why sealed?

Restrict subclasses for exhaustive when and API safety.

sealed vs enum?

Sealed for rich per-case state; enum for fixed constants.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • sealed vs enum?
  • Exhaustive when?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump