This page is no longer maintained — Please continue to the home page at

Possible violation of context bound constraint?

No replies
Sebastien Bocq
Joined: 2008-12-18,
User offline. Last seen 42 years 45 weeks ago.
I'm not sure if this is a bug but defining a default value for a contravariant typeclass of type M[-A] using M[Any] is error prone.

Suppose I define a trait:

trait Showable[-A] {
  def show(a:A):String

Then the following code can type-check:

def foo[A](a:A) = bar(a) 
def bar[A:Showable](a:A) = error("")

although obvioulsy 'foo' cannot propagate any context bound constraint to 'bar'.

This is because the companion object defines a default implicit value for Showable[Any]:

object Showable {
   implicit val anyIsShowable:Showable[Any] = new Showable[Any]{def show(a:Any) = a.toString}

This default behavior can be overriden using Scala's implicit prioritization mechanism but if you want to let the compiler catch the kind of error made with 'foo', you better define default versions for AnyRef and AnyVal instead of Any.

Any or not, the definition of 'foo' seems unsound. Should I file a ticket or do you consider this as a normal feature of the implicit resolution mechanism?


Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland