Derives

derives is one word at the end of a case class, an enum or a class declaration that asks the compiler for an instance of a type class. The compiler does not know the type class: it calls a method named derived in the companion of the class it is asked for, and that method does the work. The mechanism behind it is a Mirror, the compiler's description of the fields of a product type.

An instance written by hand

Show[A] is a type class of one method. Three instances are written below, one for a number and two for case classes, and the two of the case classes are the kind of code a program repeats for every type it has:

manual.scala

trait Show[A]: def show(value: A): String object Show: def apply[A](using instance: Show[A]): Show[A] = instance given Show[Int] = n => n.toString given Show[User] = user => s"${user.name} (${user.age})" given Show[Account] = account => s"account ${account.id} of ${account.owner}" case class User(name: String, age: Int) case class Account(id: Int, owner: String) @main def manual(): Unit = println(Show[User].show(User("Ada", 36))) println(Show[Account].show(Account(7, "Ada"))) println(Show[Int].show(42))

scala-cli run --server=false manual.scala

Ada (36)
account 7 of Ada
42

Each instance reads the fields of its type and decides how to print them, which is fine until the tenth class. A library that offers derives writes that loop once, in the companion of the type class, and a case class asks for the result.

The same shape, derived

The companion of Show declares an inline def derived that takes the Mirror of the class and builds the instance from the field labels the mirror carries. Account then writes derives Show and no instance of its own:

derived.scala

import scala.compiletime.constValueTuple import scala.deriving.Mirror trait Show[A]: def show(value: A): String object Show: def apply[A](using instance: Show[A]): Show[A] = instance given Show[Int] = n => n.toString given Show[String] = s => "\"" + s + "\"" inline def derived[A](using mirror: Mirror.ProductOf[A]): Show[A] = val labels = constValueTuple[mirror.MirroredElemLabels].productIterator.toList.map(_.toString) product(labels) private def product[A](labels: List[String]): Show[A] = new Show[A]: def show(value: A): String = val values = value.asInstanceOf[Product].productIterator.toList labels.zip(values).map((label, item) => s"$label = $item").mkString("(", ", ", ")") case class Account(id: Int, owner: String) derives Show @main def derived(): Unit = println(Show[Account].show(Account(7, "Ada"))) println(Show[Int].show(42)) println(Show[String].show("ada"))

scala-cli run --server=false derived.scala

(id = 7, owner = Ada)
42
"ada"

constValueTuple[mirror.MirroredElemLabels] is the tuple of field names, known at compile time, and the instance pairs each name with the value in the same position. That is all a product derivation is: the compiler knows the shape of the class and the companion knows what to do with it. A case class and an enum also get CanEqual from the compiler, which is what allows == between two of their cases; a plain class hierarchy asks for it with derives CanEqual.

Why Ordering cannot be derived

derives is a convention between the language and the companion of a type class, not a property of the language. A type class whose companion has no derived method cannot be derived, and the compiler says so by name:

ordering.scala

case class Point(x: Int, y: Int) derives Ordering @main def ordering(): Unit = println(List(Point(2, 1), Point(1, 2)).sorted)

mkdir -p out
scalac -color:never -d out ordering.scala 2>&1; echo "exit status: $?"

-- [E008] Not Found Error: ordering.scala:1:41 ---------------------------------
1 |case class Point(x: Int, y: Int) derives Ordering
  | ^
  | value derived is not a member of object scala.math.Ordering
1 error found
exit status: 1

Ordering has no derived member in this version of the standard library, so the ordering of a type is written with Ordering.by or by hand, as the lesson on type classes shows. The error names the companion, which is the place to look: a derives clause is only as good as the method it calls.

Related

Автор статьи: Arthur Isaev