Explain the concept and benefits of algebraic data types (ADTs) in Scala.
Instruction: Describe the use of algebraic data types in Scala and their advantages in type-safe design.
Updated
An algebraic data type combines alternatives (a sum) and fields that coexist (a product). Scala can express these with sealed traits and case classes, or with Scala 3 enums:
enum Delivery {
case Pending
case Sent(tracking: String, attempts: Int)
case Failed(reason: String)
}
def describe(value: Delivery): String = value match {
case Delivery.Pending => "pending"
case Delivery.Sent(tracking, attempts) => s"sent $tracking after $attempts attempt(s)"
case Delivery.Failed(reason) => s"failed: $reason"
}
@main def adtExample(): Unit = {
assert(describe(Delivery.Pending) == "pending")
assert(describe(Delivery.Sent("T7", 2)) == "sent T7 after 2 attempt(s)")
assert(describe(Delivery.Failed("timeout")) == "failed: timeout")
}
Delivery is the choice among three alternatives; Sent carries both a tracking string and an attempt count. This prevents a single value from being both Pending and Sent, and makes the required data for each alternative explicit. Scala ADTs
The compiler can warn about a non-exhaustive match over a closed hierarchy. Treat relevant warnings as build failures, for example with -Werror; a warning is not automatically a compilation error under every configuration. An incomplete match that reaches an uncovered case can still throw MatchError. A wildcard can also hide the need to handle a newly added variant explicitly.
An ADT is not proof of every domain invariant: this example still permits an empty tracking string or negative attempts. Add validated construction where those values are invalid. Case-class fields and nested values are not necessarily deeply immutable, and operations can still throw or have side effects. The benefit is clearer states and compiler-assisted case analysis; runtime input validation and tests remain necessary.