0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

Smart Constructors

Validated construction.

Validated Construction

A smart constructor is a factory that validates inputs before producing a value. It guarantees that any instance you hold satisfies the type's invariants.

  • The raw constructor is hidden.
  • Only validated creation is public.
class Age private (val value: Int)
object Age:
  def of(v: Int): Option[Age] =
    if v >= 0 then Some(new Age(v)) else None

object Main:
  def main(args: Array[String]): Unit =
    println(Age.of(30).map(_.value))

Private Constructor

Marking the primary constructor private stops callers from bypassing validation. The companion object becomes the single entry point.

class Percentage private (val value: Int)
object Percentage:
  def of(v: Int): Option[Percentage] =
    if v >= 0 && v <= 100 then Some(new Percentage(v)) else None

object Main:
  def main(args: Array[String]): Unit =
    println(Percentage.of(50).map(_.value))
    println(Percentage.of(150))

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