Bird
Raised Fist0
Kotlinprogramming~5 mins

Sealed classes with when exhaustive check in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style10 modes available
Recall & Review
beginner
What is a sealed class in Kotlin?
A sealed class is a special kind of class that restricts which classes can inherit from it. All subclasses must be declared in the same file, making the type hierarchy fixed and known at compile time.
Click to reveal answer
beginner
Why does Kotlin require exhaustive checks with when expressions on sealed classes?
Because the compiler knows all possible subclasses of a sealed class, it can check if a when expression covers all cases. This helps avoid missing cases and makes the code safer.
Click to reveal answer
beginner
How do you make a when expression exhaustive in Kotlin?
You include all possible subclasses of the sealed class as branches in the <code>when</code> expression. If all cases are covered, the compiler treats it as exhaustive without needing an <code>else</code> branch.
Click to reveal answer
intermediate
What happens if a <code>when</code> expression on a sealed class is not exhaustive?
The Kotlin compiler will show an error or warning if the <code>when</code> expression does not cover all subclasses of the sealed class and lacks an <code>else</code> branch, forcing you to handle all cases.
Click to reveal answer
beginner
Example: Given a sealed class Shape with subclasses Circle and Square, write an exhaustive when expression to calculate area.
sealed class Shape
class Circle(val radius: Double) : Shape()
class Square(val side: Double) : Shape()

fun area(shape: Shape): Double = when(shape) {
  is Circle -> Math.PI * shape.radius * shape.radius
  is Square -> shape.side * shape.side
}
Click to reveal answer
What is the main benefit of using sealed classes with when in Kotlin?
ASealed classes are faster than regular classes.
BYou can inherit from sealed classes anywhere.
CThe compiler can check all cases are handled.
DYou don't need to import subclasses.
If a when expression on a sealed class misses a subclass, what happens?
AThe code runs but returns null.
BThe compiler shows an error or warning.
CThe program crashes at runtime.
DNothing, it works fine.
Where must subclasses of a sealed class be declared?
AIn the same file as the sealed class.
BAnywhere in the project.
CIn a different package.
DIn a separate module.
Which keyword is used to declare a sealed class in Kotlin?
Afinal
Babstract
Copen
Dsealed
Can a sealed class have non-sealed subclasses?
AYes, but they must be in the same file.
BNo, all subclasses must be sealed.
CYes, anywhere in the project.
DNo, subclasses must be abstract.
Explain what a sealed class is and why it helps with when expressions in Kotlin.
Think about how knowing all options helps the compiler.
You got /4 concepts.
    Describe how to write an exhaustive when expression for a sealed class and what happens if you miss a case.
    Consider the compiler's role in checking completeness.
    You got /4 concepts.

      Practice

      (1/5)
      1. What is the main benefit of using sealed classes in Kotlin when combined with a when expression?
      easy
      A. The when expression becomes exhaustive, ensuring all cases are handled.
      B. It allows subclassing from any file in the project.
      C. It automatically generates getter and setter methods.
      D. It makes the class open for inheritance everywhere.

      Solution

      1. Step 1: Understand sealed classes restriction

        Sealed classes restrict subclassing to the same file, so all subclasses are known at compile time.
      2. Step 2: Effect on when expression

        This allows the when expression to be exhaustive because the compiler knows all possible subclasses.
      3. Final Answer:

        The when expression becomes exhaustive, ensuring all cases are handled. -> Option A
      4. Quick Check:

        Sealed classes + when = exhaustive check [OK]
      Hint: Sealed classes limit subclasses, making when exhaustive [OK]
      Common Mistakes:
      • Thinking sealed classes allow subclassing anywhere
      • Confusing sealed classes with data classes
      • Believing sealed classes auto-generate methods
      2. Which of the following is the correct syntax to declare a sealed class in Kotlin?
      easy
      A. sealed class Shape {}
      B. open sealed class Shape {}
      C. sealed interface Shape {}
      D. final sealed class Shape {}

      Solution

      1. Step 1: Recall sealed class declaration syntax

        In Kotlin, sealed classes are declared with the keyword sealed followed by class and the class name.
      2. Step 2: Check options for correctness

        sealed class Shape {} uses correct syntax: sealed class Shape {}. open sealed class Shape {} incorrectly adds open, which is not allowed. sealed interface Shape {} uses sealed interface, which is invalid. final sealed class Shape {} uses final sealed class, which is not allowed.
      3. Final Answer:

        sealed class Shape {} -> Option A
      4. Quick Check:

        sealed class declaration = sealed class Shape {} [OK]
      Hint: Use only 'sealed class ClassName' to declare sealed classes [OK]
      Common Mistakes:
      • Adding 'open' modifier to sealed class
      • Trying to declare sealed interfaces (not allowed)
      • Using 'final' modifier with sealed class
      3. Given the sealed class hierarchy below, what will be the output of the describe function when called with Shape.Circle(5.0)?
      sealed class Shape {
          data class Circle(val radius: Double) : Shape()
          data class Rectangle(val width: Double, val height: Double) : Shape()
      }
      
      fun describe(shape: Shape): String = when(shape) {
          is Shape.Circle -> "Circle with radius ${shape.radius}"
          is Shape.Rectangle -> "Rectangle with width ${shape.width} and height ${shape.height}"
      }
      medium
      A. Rectangle with width 5.0 and height 5.0
      B. Compilation error due to missing else branch
      C. Shape.Circle
      D. Circle with radius 5.0

      Solution

      1. Step 1: Identify the input and matching when branch

        The input is Shape.Circle(5.0). The when expression matches is Shape.Circle branch.
      2. Step 2: Evaluate the returned string

        The branch returns the string "Circle with radius 5.0" using the radius property.
      3. Final Answer:

        Circle with radius 5.0 -> Option D
      4. Quick Check:

        Input Circle(5.0) returns "Circle with radius 5.0" [OK]
      Hint: Match input type in when to get correct output string [OK]
      Common Mistakes:
      • Confusing Circle with Rectangle output
      • Expecting a compilation error due to else missing
      • Returning class name instead of formatted string
      4. Consider the following code snippet. What is the error and how can it be fixed?
      sealed class Result {
          object Success : Result()
          object Failure : Result()
      }
      
      fun handle(result: Result) = when(result) {
          is Result.Success -> "Success"
      }
      medium
      A. Runtime error: Result.Failure is not handled and causes crash.
      B. Compilation error: when expression is not exhaustive; add branch for Result.Failure.
      C. No error; code runs fine and returns null for Result.Failure.
      D. Syntax error: sealed classes cannot have object subclasses.

      Solution

      1. Step 1: Identify the sealed class subclasses

        Result has two subclasses: Success and Failure.
      2. Step 2: Check when expression branches

        The when expression only handles Result.Success, missing Result.Failure branch.
      3. Step 3: Understand Kotlin's exhaustiveness check

        Since Result is sealed, when must handle all subclasses or have an else branch. Missing Failure causes compilation error.
      4. Final Answer:

        Compilation error: when expression is not exhaustive; add branch for Result.Failure. -> Option B
      5. Quick Check:

        Sealed class when must cover all subclasses [OK]
      Hint: Add all sealed subclasses in when to avoid errors [OK]
      Common Mistakes:
      • Assuming runtime error instead of compile error
      • Ignoring missing branches in when
      • Thinking sealed classes can't have object subclasses
      5. You have a sealed class Operation with subclasses Add, Subtract, and Multiply. Write a Kotlin function calculate that takes an Operation and two integers, and returns the result of applying the operation. Which of the following implementations correctly uses an exhaustive when expression?
      hard
      A. fun calculate(op: Operation, a: Int, b: Int): Int = when(op) { is Operation.Add -> a + b else -> 0 }
      B. fun calculate(op: Operation, a: Int, b: Int): Int = when(op) { is Operation.Add -> a + b is Operation.Subtract -> a - b }
      C. fun calculate(op: Operation, a: Int, b: Int): Int = when(op) { is Operation.Add -> a + b is Operation.Subtract -> a - b is Operation.Multiply -> a * b }
      D. fun calculate(op: Operation, a: Int, b: Int): Int = when(op) { is Operation.Multiply -> a * b else -> a + b }

      Solution

      1. Step 1: Check all subclasses handled in when

        Operation has Add, Subtract, Multiply. fun calculate(op: Operation, a: Int, b: Int): Int = when(op) { is Operation.Add -> a + b is Operation.Subtract -> a - b is Operation.Multiply -> a * b } handles all three explicitly.
      2. Step 2: Verify exhaustiveness and correctness

        fun calculate(op: Operation, a: Int, b: Int): Int = when(op) { is Operation.Add -> a + b is Operation.Subtract -> a - b is Operation.Multiply -> a * b } covers all subclasses, so when is exhaustive. The other options miss some subclasses or rely on else, which is less clear.
      3. Final Answer:

        fun calculate(op: Operation, a: Int, b: Int): Int = when(op) { is Operation.Add -> a + b is Operation.Subtract -> a - b is Operation.Multiply -> a * b } -> Option C
      4. Quick Check:

        All subclasses covered in when = exhaustive [OK]
      Hint: Cover all sealed subclasses explicitly for exhaustive when [OK]
      Common Mistakes:
      • Missing some subclasses in when branches
      • Using else instead of explicit branches
      • Returning wrong default values
      Recommended

      Ready to prove it?

      Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

      10 questions~5 mineasy hard