🎓 A1Learner
🔍
0 of 45 lessons completed

Derivation

Derivation is a way for the compiler to build a type class instance for a type on its own. The word derives after a case class asks the compiler to build that instance.

Derives builds an equality instance

Point derives CanEqual. Equal points compare as true.

case class Point(x: Int, y: Int) derives CanEqual
@main def main(): Unit =
  println(Point(1, 2) == Point(1, 2))

Unequal points compare as false

The same derived instance also handles unequal points. A different second field makes the comparison false.

case class Point(x: Int, y: Int) derives CanEqual
@main def main(): Unit =
  println(Point(1, 2) == Point(1, 3))

A Mirror can rebuild a value from its fields

Summon fetches the Mirror for Point. The Mirror builds a new point from the pair 3 and 4.

import scala.deriving.Mirror
case class Point(x: Int, y: Int) derives CanEqual
@main def main(): Unit =
  val m = summon[Mirror.Of[Point]]
  val rebuilt = m.fromProduct((3, 4))
  println(rebuilt)

Example

import scala.deriving.Mirror
case class Point(x: Int, y: Int) derives CanEqual
@main def main(): Unit =
  println(Point(1, 2) == Point(1, 2))
  val m = summon[Mirror.Of[Point]]
  val rebuilt = m.fromProduct((3, 4))
  println(rebuilt)
  println(rebuilt.x)

Key points

  • Derives: a keyword after a case class that asks the compiler to build an instance.
  • CanEqual: a type class that decides whether two values of a type can be compared for equality.
  • Mirror: the compiler's description of the shape of a type, such as its fields.
  • Shape: the fields of a case class, in order.
  • Mirror use: a summoned Mirror can rebuild a value from its fields.

In this example, Point derives CanEqual, so the first print compares equal points. Next, summon fetches the Mirror for Point. Then the Mirror rebuilds a point from 3 and 4. The last prints show the rebuilt point and its first field.

Note

with derives, no hand-written instance is needed for the comparison.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What does derives CanEqual do for Point?