Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An introduction to algebraic data types (basics) in Scala...some things need to get cleaned up, but only after you grasp the basics. Part 1
package net.susanpotter.algdt
sealed trait Order {
def execute: Unit // ignore that Unit return type is not a great idea...
}
case class MarketOrder extends Order {
def execute {
println "executing market order"
}
}
case class LimitOrder extends Order {
def execute {
println "executing limit order"
}
}
// Note that the above are mutually exclusive. An order is either a market or limit order not both.
// This is what is called as a Sum type and MarketOrder and LimitOrder are value constructors for the
// type Order. When defining your interfaces you should never use the value constructors only the type.
// Now a product type
// assumes a type of
sealed trait Currency
case class USD extends Currency
case class CAD extends Currency
case class EUR extends Currency
case class GBP extends Currency
case class Money(currency: Currency, amount: Int)
sealed trait Period
case class Hour extends Period
case class Day extends Period
case class Week extends Period
case class Month extends Period
case class Duty(description: String, skillRequired: String)
case class Project(name: String, description: String, deliverables: Seq[String])
sealed trait Worker
case class Employee(title: String, salary: Money, duties: Seq[Duty]) extends Worker
case class Contractor(rate: Money, period: Period, projects: Seq[Project]) extends Worker
// A small domain but modeled with algebraic data types (mostly).
// Currency is a sum type again
// So is Period and it's case classes
// Worker has multually exclusive sum types that are products
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment