Type classes
A type class is a trait that describes what a type can do, with one instance per type instead of a method on the type. The method that needs the capability asks for the instance in a using parameter, so a new type joins the club by providing an instance and no existing type is touched. The pattern is the reason Ordering, Show and the JSON codecs of a library look the way they do.
The trait, the instances and the method
Json[A] turns a value into text. The companion holds an instance for a number, one for a string, and one for a list of anything that already has an instance. toJson asks for the instance with a using parameter, and toJsonContext writes the same request as a context bound:
type_classes.scala
trait Json[A]:
def encode(value: A): String
object Json:
def apply[A](using instance: Json[A]): Json[A] = instance
given Json[Int] = n => n.toString
given Json[String] = s => "\"" + s + "\""
given [A](using json: Json[A]): Json[List[A]] = xs => xs.map(json.encode).mkString("[", ",", "]")
case class User(name: String, age: Int)
given Json[User] = user => s"""{"name":${Json[String].encode(user.name)},"age":${user.age}}"""
def toJson[A](value: A)(using json: Json[A]): String = json.encode(value)
def toJsonContext[A: Json](value: A): String = summon[Json[A]].encode(value)
@main def type_classes(): Unit =
println(toJson(42))
println(toJson("scala"))
println(toJson(List(1, 2, 3)))
println(toJson(List("a", "b")))
println(toJson(User("Ada", 36)))
println(toJsonContext(List(7)))
scala-cli run --server=false type_classes.scala
42
"scala"
[1,2,3]
["a","b"]
{"name":"Ada","age":36}
[7]
toJson(List(1, 2, 3)) needs a Json[List[Int]] and no such instance was written: the generic one builds it from Json[Int], which is the whole point of the pattern. The User instance sits beside the case class rather than in the companion of Json, and it is found all the same, because a given in the enclosing scope is in scope at the call. [A: Json] is the short form of (using Json[A]) and is read as "A for which a Json exists".
A type class from the library
Ordering[A] is the type class the sorts of the collections use, and a program supplies one for its own type the same way. Ordering.by builds it from a key:
versions.scala
case class Version(major: Int, minor: Int)
given Ordering[Version] = Ordering.by(version => (version.major, version.minor))
@main def versions(): Unit =
val versions = List(Version(1, 10), Version(2, 0), Version(1, 9))
println(versions.sorted)
println(versions.max)
println(versions.minBy(version => (version.major, version.minor)))
scala-cli run --server=false versions.scala
List(Version(1,9), Version(1,10), Version(2,0))
Version(2,0)
Version(1,9)
With the instance in scope, sorted, max and minBy work on Version without a change to the class or to the collection code. Ordering.by takes a function to a type that already has an ordering, and a tuple of two fields orders by the first and then the second, which is why the versions sort by major and then by minor.
Related
- given and using: the mechanism the instance is passed by.
- groupBy, sorting and splitting: the sorts that read the Ordering.
- Derives: the instance the compiler writes for a case class.
- Generics: the type parameter the trait is written on.
Article author: Arthur Isaev