0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

Newtypes

Type-safe wrappers.

Type-Safe Wrappers

A newtype is a distinct type that wraps a single underlying value. It prevents mixing up values that share a primitive representation, like a UserId and a ProductId that are both Ints.

case class UserId(value: Int)
case class ProductId(value: Int)

object Main:
  def main(args: Array[String]): Unit =
    val u = UserId(1)
    val p = ProductId(1)
    println(u.value == p.value) // values equal, types differ

The Primitive Obsession Problem

Primitive obsession is overusing String and Int for domain concepts. It allows nonsense like passing an email where a name belongs. Newtypes fix this by giving each concept its own type.

case class Email(value: String)
case class City(value: String)

object Main:
  def greet(c: City): String = s"Welcome to ${c.value}"

  def main(args: Array[String]): Unit =
    println(greet(City("Berlin")))

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