For this post I’ll consider the following simple case class unless otherwise specified: case class Person(lastname: String, firstname: String, birthYear: Int)
In this post:
Common knowledge about case classes Not so common knowledge about case classes Defining a case class using the curried form Defining a case class with a private constructor For the most curious ones Final Notes Common knowledge about case classes When you declare a case class the Scala compiler does the following for you:
One of the advantages of using a statically typed language is that you can use the type system to enforce some constraints. Scala provides self-recursive types, aka F-bounded polymorphic types that–along with self types–let you put powerful constraint to your type definitions.
Self-recursive type definition Terminology apart, let me show you one of the use cases where this could be useful. Consider the following example which does not use a self-recursive type:
A simple internal DSL in Scala for money-related operations Source code: Scala DSL for money-related operations
This Domain-Specific Language (DSL) lets you perform operations among different currencies, by transparently doing all internal conversions. The conversion map is injected implicitly by the client code.
Usage Example Here’s a simple usage example:
import com.lambdista.money._ import com.lambdista.money.Currency._ object Main { def main(args: Array[String]): Unit = { val conversion: Conversion = Map( (GBP, EUR) -> 1.