CodeBlanks Logo Icon CodeBlanks

sealed class

Learn closed hierarchies with sealed class.

sealed class

A sealed class defines a closed hierarchy where the subtypes are limited and known. All subtypes must be declared in the same file (or in Kotlin 2 the same module).

Example: sealed class Status; object Loading : Status(); object Done : Status(). Status has only two subtypes: Loading and Done. This closure means the compiler knows all subtypes; when expressions can be exhaustive. Sealed classes are abstract; they cannot be instantiated directly.

Subtypes

Subtypes of a sealed class can be a class, a data class or an object. Each one inherits the sealed class.

Example: sealed class Status; object Loading : Status(); data class Error(val msg: String) : Status(). Here Loading is an object (single instance), Error is a data class (separate instance per error). Making a subtype an object expresses a single state; a data class expresses a state with fields. The sealed class itself is abstract.

Practice Define the Status sealed class

Define a sealed class named Status. Add two subtypes: object Loading : Status() and object Done : Status(). In main declare val s: Status = Done and print s with println.

Starter code

Main.kt
// Define the Status sealed class
// object Loading and object Done subtypes
// declare a Status variable in main, print

Sample solution

Main.kt
sealed class Status
object Loading : Status()
object Done : Status()

fun main() {
    val s: Status = Done
    println(s)
}

Expected output

Done

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does a <strong>sealed class</strong> provide?

  • A closed hierarchy with known subtypes Correct answer
  • The class can be instantiated directly
  • Subclasses can be defined outside the file
  • New subtypes can be added at runtime

Explanation: A sealed class defines a closed hierarchy with known subtypes.

2 Complete the sealed class definition

Question
sealed ____ Status
object Loading : Status()
object Done : Status()
Answer
sealed class Status
object Loading : Status()
object Done : Status()

Explanation: sealed class declares a closed hierarchy.

3 Match the sealed class parts

Term Meaning
sealed class Status Closed base class
object Loading Loading state
object Done Done state
: Status() Inheritance and constructor

All lessons in Intermediate