sealed keyword in scala
What is the sealed Keyword in Scala
Introduction
Scala is a powerful programming language that blends functional and object-oriented programming paradigms. One of the key features of Scala is its type safety and pattern matching capabilities. The sealed
keyword in Scala plays a crucial role in ensuring exhaustive pattern matching and controlled inheritance. In this article, we will explore the sealed
keyword in detail, understand its importance, and see practical examples of how it can be used effectively.
sealed
Keyword in Scala?
The sealed
keyword in Scala is used to restrict the inheritance of a class or trait to the same file in which it is declared. This means that all subclasses of a sealed
class or trait must be defined within the same source file, providing better control over the class hierarchy.
sealed
sealed trait Animal
case class Dog(name: String) extends Animal
case class Cat(name: String) extends Animal
In this example:
Animal
is a sealed
trait.Dog
and Cat
are case classes extending Animal
.Animal
outside this file will result in a compilation error.sealed
in Scala?
Using sealed
in Scala offers several advantages:
Since the compiler knows all subclasses of a sealed
trait or class, it can enforce exhaustive pattern matching.
def identifyAnimal(animal: Animal): String = animal match {
case MyDog(name) => s"It's a dog named $name"
case MyCat(name) => s"It's a cat named $name"
}
If a new subclass is added to Animal
, the compiler will warn us about missing cases in pattern matching, ensuring robust and error-free code.
By restricting inheritance, sealed
makes code more maintainable. Developers can quickly understand all possible subclasses without searching multiple files.
Since all subclasses must be in the same file, the compiler can verify completeness and correctness at compile time, reducing runtime errors.
Scala provides other modifiers like final
and abstract
, which are often confused with sealed
. Here’s a quick comparison:
Modifier | Inheritance Allowed? | Location Restriction | Pattern Matching Benefits |
---|---|---|---|
sealed |
Yes, within the same file | Restricted to the file | Yes |
final |
No | No restriction | No |
abstract |
Yes | No restriction | No |
Sealed traits are commonly used in Algebraic Data Types (ADTs), which are useful in functional programming.
sealed trait Result
case class Success(data: String) extends Result
case class Failure(error: String) extends Result
def handleResult(result: Result): String = result match {
case Success(data) => s"Success: $data"
case Failure(error) => s"Error: $error"
}
This pattern ensures that we handle all possible cases of Result
at compile time.
The sealed
keyword in Scala is a powerful feature that helps control inheritance and ensures exhaustive pattern matching. It improves code maintainability, safety, and clarity. By using sealed
effectively, Scala developers can write more robust and predictable code.