In Scala, the sealed modifier is used to restrict the inheritance of a trait or class to the same file where it is defined. This ensures that all subclasses are known at compile-time, enhancing type safety and enabling exhaustive pattern matching. By using sealed, devs can create a closed hierarchy of types, which is particularly useful in defining algebraic data types. The compiler can then warn if a match expression is missing any case, providing better reliability and robustness in the code. The sealed modifier thus plays a crucial role in ensuring the integrity of the type system.
The code defines a sealed trait Shape and three case classes extending it: Circle, Rectangle, and Square. A ShapeAreaCalculator object contains a function calcArea to compute the area of these shapes using pattern matching. The main method creates a list of shapes and prints their areas. This example demonstrates the use of the sealed modifier for safe pattern matching.
#programming #coding #java #scala