What is a “context bound” in Scala?

Robert’s answer covers the techinal details of Context Bounds. I’ll give you my interpretation of their meaning.

In Scala a View Bound (A <% B) captures the concept of ‘can be seen as’ (whereas an upper bound <: captures the concept of ‘is a’). A context bound (A : C) says ‘has a’ about a type. You can read the examples about manifests as “T has a Manifest“. The example you linked to about Ordered vs Ordering illustrates the difference. A method

def example[T <% Ordered[T]](param: T)

says that the parameter can be seen as an Ordered. Compare with

def example[T : Ordering](param: T)

which says that the parameter has an associated Ordering.

In terms of use, it took a while for conventions to be established, but context bounds are preferred over view bounds (view bounds are now deprecated). One suggestion is that a context bound is preferred when you need to transfer an implicit definition from one scope to another without needing to refer to it directly (this is certainly the case for the ClassManifest used to create an array).

Another way of thinking about view bounds and context bounds is that the first transfers implicit conversions from the caller’s scope. The second transfers implicit objects from the caller’s scope.

Leave a Comment