Bird
Raised Fist0
Kotlinprogramming~20 mins

Sealed classes for restricted hierarchies in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Sealed Class Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of sealed class when matching with 'when'
What is the output of this Kotlin code using a sealed class and a when expression?
Kotlin
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}"
}

fun main() {
    val shape: Shape = Shape.Circle(5.0)
    println(describe(shape))
}
ACircle with radius 5.0
BRectangle with width 5.0 and height 5.0
CCompilation error: 'when' expression is not exhaustive
DRuntime error: Unhandled type
Attempts:
2 left
💡 Hint
Think about how sealed classes allow the compiler to know all subclasses and how 'when' handles them.
❓ Predict Output
intermediate
2:00remaining
Exhaustiveness check with sealed classes
What happens if you add a new subclass to a sealed class but forget to update the when expression that matches on it?
Kotlin
sealed class Result {
    object Success : Result()
    object Failure : Result()
    object Loading : Result()
}

fun handle(result: Result): String = when(result) {
    Result.Success -> "Success"
    Result.Failure -> "Failure"
}

fun main() {
    println(handle(Result.Loading))
}
APrints 'Failure'
BCompilation error: 'when' expression is not exhaustive
CPrints 'Success'
DRuntime error: Unhandled type
Attempts:
2 left
💡 Hint
Sealed classes let the compiler check if all subclasses are handled in 'when'.
🔧 Debug
advanced
2:00remaining
Why does this sealed class code fail to compile?
Identify the reason why this Kotlin code with sealed classes does not compile.
Kotlin
sealed class Animal
class Dog : Animal()
class Cat : Animal()

fun sound(animal: Animal) = when(animal) {
    is Dog -> "Bark"
    is Cat -> "Meow"
}
ASealed class subclasses must be declared in the same file
BMissing 'else' branch in 'when' expression
CCannot use 'is' checks with sealed classes
DSealed class cannot have subclasses
Attempts:
2 left
💡 Hint
Think about Kotlin's rules for sealed class subclass declarations.
📝 Syntax
advanced
2:00remaining
Correct syntax for sealed interface and its implementations
Which option shows the correct Kotlin syntax for a sealed interface and two implementations?
A
sealed interface Vehicle
sealed interface Car : Vehicle
sealed interface Bike : Vehicle
B
sealed interface Vehicle {
    class Car : Vehicle
    class Bike : Vehicle
}
C
sealed interface Vehicle
sealed class Car : Vehicle()
sealed class Bike : Vehicle()
D
sealed interface Vehicle
class Car : Vehicle
class Bike : Vehicle
Attempts:
2 left
💡 Hint
Sealed interfaces can be implemented by classes declared in the same file.
🚀 Application
expert
2:00remaining
Number of subclasses in sealed class hierarchy
Given this sealed class hierarchy, how many direct subclasses does the sealed class Operation have?
Kotlin
sealed class Operation {
    data class Add(val x: Int, val y: Int) : Operation()
    data class Subtract(val x: Int, val y: Int) : Operation()
    sealed class Multiply : Operation() {
        data class Simple(val x: Int, val y: Int) : Multiply()
        data class Complex(val x: Int, val y: Int, val z: Int) : Multiply()
    }
}
A4
B5
C3
D2
Attempts:
2 left
💡 Hint
Count only the immediate subclasses declared directly under Operation.

Practice

(1/5)
1. What is the main purpose of using sealed classes in Kotlin?
easy
A. To create classes that cannot be instantiated
B. To allow any class in any file to inherit from it
C. To restrict which classes can inherit from it, all in the same file
D. To automatically generate data classes

Solution

  1. Step 1: Understand sealed class inheritance rules

    Sealed classes restrict subclassing to the same file, limiting which classes can extend them.
  2. Step 2: Compare options with sealed class purpose

    Only To restrict which classes can inherit from it, all in the same file correctly describes this restriction; others describe unrelated features.
  3. Final Answer:

    To restrict which classes can inherit from it, all in the same file -> Option C
  4. Quick Check:

    Sealed classes restrict inheritance = A [OK]
Hint: Sealed classes limit subclasses to one file only [OK]
Common Mistakes:
  • Thinking sealed classes prevent instantiation
  • Confusing sealed classes with abstract classes
  • Believing sealed classes allow open inheritance
2. Which of the following is the correct syntax to declare a sealed class named Shape in Kotlin?
easy
A. abstract sealed class Shape
B. open sealed class Shape {}
C. sealed interface Shape {}
D. sealed class Shape {}

Solution

  1. Step 1: Recall sealed class declaration syntax

    Sealed classes are declared with the keyword sealed class followed by the name and body.
  2. Step 2: Check each option's correctness

    sealed class Shape {} matches the correct syntax. open sealed class Shape {} wrongly combines open and sealed. sealed interface Shape {} uses sealed interface which is invalid. abstract sealed class Shape {} wrongly combines abstract and sealed.
  3. Final Answer:

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

    Correct sealed class syntax = D [OK]
Hint: Use only 'sealed class ClassName {}' to declare sealed classes [OK]
Common Mistakes:
  • Adding 'open' or 'abstract' keywords with sealed
  • Using 'sealed interface' instead of 'sealed class'
  • Forgetting curly braces after class name
3. Consider the following Kotlin code using sealed classes:
sealed class Result {
    data class Success(val data: String) : Result()
    object Failure : Result()
}

fun handle(result: Result) = when(result) {
    is Result.Success -> "Data: ${result.data}"
    is Result.Failure -> "Failed"
}

println(handle(Result.Success("OK")))

What is the output when this code runs?
medium
A. "Data: OK"
B. "Failed"
C. Compilation error due to missing else branch
D. Runtime exception

Solution

  1. Step 1: Understand sealed class and when expression

    The sealed class Result has two subclasses: Success and Failure. The when expression covers both cases without else.
  2. Step 2: Trace the function call with Success("OK")

    The argument is Result.Success("OK"), so the first branch matches, returning "Data: OK".
  3. Final Answer:

    "Data: OK" -> Option A
  4. Quick Check:

    Sealed class when covers all cases = "Data: OK" [OK]
Hint: Sealed classes allow exhaustive when without else [OK]
Common Mistakes:
  • Thinking else branch is required for sealed classes
  • Confusing Success and Failure outputs
  • Expecting runtime errors from sealed classes
4. The following Kotlin code tries to compile but fails. What is the error?
sealed class Animal
class Dog : Animal()
class Cat : Animal()

Why does this code cause a compilation error?
medium
A. Sealed classes cannot have subclasses
B. Subclasses Dog and Cat must be declared in the same file as Animal
C. Dog and Cat must be declared as sealed classes too
D. Animal must be declared as an abstract class instead

Solution

  1. Step 1: Recall sealed class subclass rules

    Sealed classes restrict subclasses to be declared in the same file.
  2. Step 2: Identify the error cause

    Dog and Cat are subclasses but declared outside the sealed class file, causing compilation error.
  3. Final Answer:

    Subclasses Dog and Cat must be declared in the same file as Animal -> Option B
  4. Quick Check:

    Sealed subclasses must be in same file = B [OK]
Hint: All sealed subclasses must be in the same file [OK]
Common Mistakes:
  • Thinking sealed classes forbid any subclassing
  • Believing subclasses must be sealed too
  • Confusing sealed with abstract class rules
5. You want to model a fixed set of user roles in Kotlin using sealed classes: Admin, Guest, and Member. Which approach correctly uses sealed classes to restrict roles and safely handle all cases?
hard
A. sealed class UserRole { object Admin : UserRole() object Guest : UserRole() object Member : UserRole() } fun describe(role: UserRole) = when(role) { is UserRole.Admin -> "Admin user" is UserRole.Guest -> "Guest user" is UserRole.Member -> "Member user" }
B. open class UserRole class Admin : UserRole() class Guest : UserRole() class Member : UserRole() fun describe(role: UserRole) = when(role) { is Admin -> "Admin user" is Guest -> "Guest user" is Member -> "Member user" else -> "Unknown" }
C. sealed interface UserRole { object Admin : UserRole object Guest : UserRole object Member : UserRole } fun describe(role: UserRole) = when(role) { UserRole.Admin -> "Admin user" UserRole.Guest -> "Guest user" UserRole.Member -> "Member user" }
D. abstract class UserRole object Admin : UserRole() object Guest : UserRole() object Member : UserRole() fun describe(role: UserRole) = when(role) { is Admin -> "Admin user" is Guest -> "Guest user" is Member -> "Member user" }

Solution

  1. Step 1: Use sealed class to restrict subclasses

    sealed class UserRole { object Admin : UserRole() object Guest : UserRole() object Member : UserRole() } fun describe(role: UserRole) = when(role) { is UserRole.Admin -> "Admin user" is UserRole.Guest -> "Guest user" is UserRole.Member -> "Member user" } declares a sealed class with all subclasses as objects inside the same file, restricting roles properly.
  2. Step 2: Check safe handling with exhaustive when

    The when expression covers all subclasses without else, ensuring safe handling.
  3. Final Answer:

    sealed class UserRole { object Admin : UserRole() object Guest : UserRole() object Member : UserRole() } fun describe(role: UserRole) = when(role) { is UserRole.Admin -> "Admin user" is UserRole.Guest -> "Guest user" is UserRole.Member -> "Member user" } -> Option A
  4. Quick Check:

    Sealed class + exhaustive when = safe fixed roles [OK]
Hint: Use sealed class with all subclasses inside one file [OK]
Common Mistakes:
  • Using open or abstract classes without sealing
  • Missing exhaustive when branches
  • Using sealed interface incorrectly
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