scalascala-2.8context-bound

What is a "context bound" in Scala?


One of the new features of Scala 2.8 are context bounds. What is a context bound and where is it useful?

Of course I searched first (and found for example this) but I couldn't find any really clear and detailed information.


Solution

  • Did you find this article? It covers the new context bound feature, within the context of array improvements.

    Generally, a type parameter with a context bound is of the form [T: Bound]; it is expanded to plain type parameter T together with an implicit parameter of type Bound[T].

    Consider the method tabulate which forms an array from the results of applying a given function f on a range of numbers from 0 until a given length. Up to Scala 2.7, tabulate could be written as follows:

    def tabulate[T](len: Int, f: Int => T) = {
        val xs = new Array[T](len)
        for (i <- 0 until len) xs(i) = f(i)
        xs
    }
    

    In Scala 2.8 this is no longer possible, because runtime information is necessary to create the right representation of Array[T]. One needs to provide this information by passing a ClassManifest[T] into the method as an implicit parameter:

    def tabulate[T](len: Int, f: Int => T)(implicit m: ClassManifest[T]) = {
        val xs = new Array[T](len)
        for (i <- 0 until len) xs(i) = f(i)
        xs
    }
    

    As a shorthand form, a context bound can be used on the type parameter T instead, giving:

    def tabulate[T: ClassManifest](len: Int, f: Int => T) = {
        val xs = new Array[T](len)
        for (i <- 0 until len) xs(i) = f(i)
        xs
    }