0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

Modeling with ADTs

Make illegal states unrepresentable.

Algebraic Data Types

Algebraic data types (ADTs) are the foundation of functional domain modeling. They combine product types (AND) and sum types (OR) to describe data precisely.

  • Product: a record with several fields.
  • Sum: a choice among several variants.
case class Point(x: Int, y: Int) // product type

object Main:
  def main(args: Array[String]): Unit =
    println(Point(1, 2))

Product Types

A product type bundles values together. In Scala a case class is a product: an instance holds all its fields at once.

case class User(name: String, age: Int)

object Main:
  def main(args: Array[String]): Unit =
    val u = User("Ada", 36)
    println(u.name)
    println(u.age)

All lessons in this course

  1. Modeling with ADTs
  2. Smart Constructors
  3. Newtypes
  4. Composing Domains
← Back to Scala for Backend Engineering & Functional Programming