Explain the differences and practical uses of view bounds and context bounds in Scala.

Instruction: Discuss the differences between view bounds and context bounds, including examples of their practical applications.

Context: Aims to assess the candidate's understanding of Scala's type constraints mechanisms, their differences, and how they are applied in real-world scenarios.

Updated

Official answer

A view bound requests a conversion; a context bound requests evidence such as a type-class instance. Neither means that the type parameter is a subtype of the bound.

In legacy Scala 2, [A <% Int] requests implicit conversion evidence from A to Int. An operation that actually needs an Int may use that conversion. The old example println(x) is misleading: printing accepts a general value and need not exercise the conversion. View bounds are deprecated in Scala 2 and removed in Scala 3. For new code, prefer an explicit conversion parameter when conversion is part of the contract, rather than copying <% syntax.

A context bound [A: Ordering] requires an available Ordering[A]. It supports operations on values of type A without converting those values to a different type. These are equivalent Scala 3 sorting methods for this simple case:

def sortedWithBound[A: Ordering](xs: List[A]): List[A] =
  xs.sorted

def sortedWithParameter[A](xs: List[A])(using order: Ordering[A]): List[A] =
  xs.sorted(using order)

assert(sortedWithBound(List(3, 1, 2)) == List(1, 2, 3))
assert(sortedWithParameter(List(3, 1, 2)) == List(1, 2, 3))

The ordering can be changed by supplying different evidence, for example a reverse ordering. Choose context bounds when a generic algorithm needs a capability such as ordering, encoding or numeric operations. Choose an explicit function when the algorithm deliberately transforms one representation into another. Keep syntax and evidence rules tied to the Scala version in use; type-class evidence does not automatically make an arbitrary implementation correct.

Sources

Scala 3 migration: view bounds; Scala 3 context bounds.

Related Questions