Sunday, 25 December 2011

Context bounds for type parameters in Scala

I thought I knew all type parameter bounds until recently, when I discovered the context bounds.

Let's have a look at the example:
def sum[T](list: Seq[T])(implicit typeClass : AddTypeClass[T]) = {
    list.reduce(typeClass.add(_,_))
  }

There is nothing unusual in here. Function sum needs a typeclass to perform it's operation.

Now let's express the same using context bounds:
def sum[T: AddTypeClass](list: List[T]) = {
    val typeClass = implicitly[AddTypeClass[T]]
    list.reduce(typeClass.add(_,_))
  }

Expression [T: AddTypeClass] means: "for some T such that, there exists a type AddTypeClass[T]". This is called context bounds.
Now we just need to get hold of an instance of type AddTypeClass[T]. We can use the function implicitly from Predef.

The definition of implicitly is as follows:
def implicitly[T](implicit e: T) = e

Enjoy!

No comments:

Post a Comment