Pattern matching for product ADTs

Pattern matching shows its real power when used for product and hybrid ADTs. In such cases, we can match the actual values of the data types. Let's see how we would implement a functionality to calculate the area of a shape, as defined previously:

object Shape {  def area(shape: Shape): Double =    shape match {      case Circle(Point(x, y), radius) => Math.PI * Math.pow(radius, 2)      case Rectangle(_, h, w) => h * w    }}

When matching, we can ignore values we don't care about. For the area, we don't really need the position information. In the preceding code, we just showed two different ways in which a matching is possible. The _ operator can be anywhere in the match statement, and it will just ignore the value it is ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.