Explain the role of 'view bounds' in Scala and discuss their deprecation.

Instruction: Describe historical view bounds, their removal in Scala 3, and when explicit conversion evidence or a type-class context bound is appropriate.

Context: This question is designed to evaluate the candidate's knowledge of Scala's evolving type system, including advanced features and their historical context.

Updated

A historical view bound such as [A <% Long] required an implicit conversion from A to Long. It expressed convertibility, not the subtype relationship expressed by <:. View bounds are deprecated in Scala 2.13 and are not supported in Scala 3.

A migration can make the conversion evidence explicit and call it explicitly:

def converted[A](value: A)(using convert: A => Long): Long =
  convert(value)

def minimum[A: Ordering](left: A, right: A): A =
  summon[Ordering[A]].min(left, right)

@main def boundsExample(): Unit = {
  assert(converted(12)(using (n: Int) => n.toLong) == 12L)
  assert(minimum(8, 3) == 3)
  assert(minimum("b", "a") == "a")
}

The second method illustrates a different contract: a context bound [A: Ordering] requests an Ordering[A] instance. It does not convert A into another type. A type-class capability is often clearer when the real requirement is an operation such as ordering, serialization or arithmetic, but replacing a view bound with a context bound is not a semantics-preserving punctuation change.

During migration, inspect the required behavior and binary/API compatibility, make conversion calls visible where needed and test resolution at call sites. In Scala 3, a contextual function value A => B is not automatically used as an implicit view. View-bound migration Context bounds

Related Questions