Google News
logo
Scala - Interview Questions
What is the purpose of the 'sealed' keyword in Scala?
The `sealed` keyword in Scala is used to restrict the inheritance of classes or traits within a defined scope. When a class or trait is marked as `sealed`, it means that it can only be extended within the same source file or compilation unit.

The primary purpose of using the `sealed` keyword is to enable pattern matching exhaustiveness checks at compile-time. When pattern matching is used with a `sealed` class or trait, the compiler can analyze the patterns and provide warnings if there are any missing cases. This ensures that all possible cases are handled, reducing the likelihood of bugs or incomplete pattern matching logic.

Here's an example to illustrate the use of the `sealed` keyword :
sealed abstract class Fruit
case class Apple() extends Fruit
case class Banana() extends Fruit

def describeFruit(fruit: Fruit): String = fruit match {
  case Apple() => "This is an apple."
  case Banana() => "This is a banana."
}

val fruit: Fruit = Apple()
val description = describeFruit(fruit)
println(description)  // Output: This is an apple.​
In this example, the `Fruit` class is declared as `sealed`, and it is extended by two case classes: `Apple` and `Banana`. The `describeFruit` function uses pattern matching to provide descriptions for different kinds of fruits. Since the `Fruit` class is `sealed`, the compiler can check if all possible cases are handled in the pattern match.

If we were to add another case class, such as `Orange`, and not handle it in the pattern match, the compiler would generate a warning indicating that the pattern match is not exhaustive. This serves as a safety mechanism to catch potential bugs and ensure that all cases are explicitly handled.

By marking classes or traits as `sealed`, you can enforce a closed set of subclasses, enabling exhaustive pattern matching checks at compile-time. It helps improve code correctness, maintainability, and readability by making it easier to reason about all possible cases in a pattern match and avoiding unexpected behavior due to missing cases.
Advertisement