Explain the significance of the 'sealed' keyword in Scala.

Instruction: Discuss how the 'sealed' keyword affects trait or class inheritance and its use cases in Scala.

Context: This question assesses the candidate's understanding of the 'sealed' keyword, its impact on class hierarchies, and how it facilitates more exhaustive type checking, especially in pattern matching scenarios.

Updated

sealed restricts direct subclasses of a class or trait to the same source file. This lets the compiler reason about the direct alternatives when checking pattern matches.

sealed trait PaymentMethod
final case class Card(lastFour: String) extends PaymentMethod
case object BankTransfer extends PaymentMethod

def label(method: PaymentMethod): String = method match {
  case Card(lastFour) => s"Card ending $lastFour"
  case BankTransfer => "Bank transfer"
}
@main def sealedExample(): Unit = {
  assert(label(Card("1234")) == "Card ending 1234")
  assert(label(BankTransfer) == "Bank transfer")
}

The restriction applies to direct children: an unsealed, non-final child may itself be extended elsewhere. Use final or further sealed hierarchies as appropriate when the entire hierarchy needs controlled alternatives. Sealed hierarchies and matching

An incomplete match can produce a warning and can throw MatchError at runtime; sealed does not automatically make every warning a compilation error. Configure relevant warnings as errors where appropriate. A wildcard may conceal the need to review a newly added case. Sealing also does not validate fields or prove business correctness: the example still accepts an invalid card suffix.

Related Questions