Scala Design Patterns.
上QQ阅读APP看书,第一时间看更新

Hybrid ADTs

Hybrid algebraic data types represent a combination of the sum and product ones we described previously. This means that we can have specific value constructors, but these value constructors also provide parameters in order to wrap other types.

Let's see an example. Imagine we are writing a drawing application:

sealed abstract trait Shape
case class Circle(radius: Double) extends Shape
case class Rectangle(height: Double, width: Double) extends Shape

We have different shapes. The preceding example shows a sum ADT because we have the specific Circle and Rectangle value constructors. Also, we have a product ADT because the constructors take extra parameters.

Let's expand our classes a bit. When drawing our shapes, we need to know their positions. This is why we can add a Point class that holds the x and y coordinates:

case class Point(x: Double, y: Double)

sealed abstract trait Shape
case class Circle(centre: Point, radius: Double) extends Shape
case class Rectangle(topLeft: Point, height: Double, width: Double) extends Shape

This should hopefully clarify what ADTs are in Scala and how they can be used.