SCALA ALGEBRAIC DATA TYPES

  • date 18th February, 2021 |
  • by Prwatech |
  • 0 Comments

The Sum type

The Sum type is also referred to as an “enumerated type” because you simply enumerate all of the possible instances of the type. A few important points about this are:

Sum types are typically created with a sealed trait as the base type, with instances created as case objects. You use a sealed trait because you don’t want them to be extended.

The number of enumerated types you list is the only possible instance of the base type. In this example, The wall has only four possible sides.

The Product type

The second type of ADT is known as a “Product type.” Its name comes from the fact that you use the Scala case class constructor to create a data type whose number of possible concrete instances can be determined by multiplying the number of possibilities of all of its constructor fields.

case class Prwatech (
    b1: Training,
    b2: Institute
)

Hybrid types

These types represent a sum type because the shape is a circle or a Rectangle; a circle is a product type because it has a radius, and a Rectangle is also a product type because it has a width and a height..

There are other variations of these possibilities, which is why I refer to all other combinations as hybrid types. For instance, the class in the domain modeling lessons is a product type that contains three types:

case class Prwatech (
    DataScience: DataScience,
    BigData: BigData,
    ElasticSearch: Seq[ElasticSearch]
)

Quick Support

image image