Discuss the implementation and use of 'Context Bounds' in Scala.
Instruction: Explain what context bounds are and how they are used in Scala, with a specific example.
Updated
A context bound requests a type-class instance associated with a type parameter. For example, [A: Ordering] adds a contextual requirement for Ordering[A]; it does not mean that A extends Ordering[A] or is converted into it.
def ordered[A: Ordering](values: List[A]): List[A] =
values.sorted
def orderedExplicit[A](values: List[A])
(using order: Ordering[A]): List[A] =
values.sorted(using order)
@main def contextBoundExample(): Unit = {
assert(ordered(List(3, 1, 2)) == List(1, 2, 3))
assert(orderedExplicit(List("b", "a")) == List("a", "b"))
assert(ordered(List(1, 2, 3))(using Ordering.Int.reverse)
== List(3, 2, 1))
}
The two differently named methods show shorthand and expanded Scala 3 forms without defining conflicting overloads. summon[Ordering[A]] can retrieve the context-bound instance inside a method when it is needed explicitly. An eligible instance must be available at the call site, through ordinary contextual resolution, or supplied explicitly. Context bounds
Type-class constraints express the required capability without making domain classes inherit from a particular interface. They do not automatically validate runtime data or prove laws such as transitivity for an arbitrary custom ordering. More elaborate context-bound syntax has version-specific rules, so keep the syntax compatible with the project's Scala version.
Related Questions
-
medium
-
hard
-
hard
-
hard