This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Type classes and implicits

1 reply
Ka Ter
Joined: 2011-10-05,
User offline. Last seen 42 years 45 weeks ago.

Hi all,

I'm playing with type classes and implicits and don't understand why
both of the println lines below produce the compiler error:

could not find implicit value for evidence parameter of type
GenericBased[scala.collection.immutable.Set]

I surely understand the message but I don't understand why the mentioned
type could not be found. Why can't the compiler relate a Set with a
Traversable? Any thoughts?

(I need the GenericBasedWrapper only, as Scala doesn't support some kind
of implicit infix functions).

My code:
=========
import scala.collection.parallel.ParIterable

object Test extends App
{
implicit val traversableBased = TraversableBased
implicit val parallelBased = ParallelBased

implicit def toGenericBasedWrapper[A, C[A] : GenericBased](source:
C[A]): GenericBasedWrapper[A, C] = new GenericBasedWrapper[A, C](source)

println(Set[Int](1, 2, 3).doSomething((set: Set[Int]) => set.map(a
=> a + 1)))
println(Set[Int](1, 2, 3).doSomething(set => set.map(a => a + 1)))
}

class GenericBased[+C[_]]
{
def doSomething[A](source: C[A], f: C[A] => C[A]): C[A] = f(source)
}

class GenericBasedWrapper[A, +C[_]: GenericBased](source: C[A])
{
def doSomething(f: C[A] => C[A]): C[A] =
implicitly[GenericBased[C]].doSomething[A](source, f)
}

object TraversableBased extends GenericBased[Traversable]
object ParallelBased extends GenericBased[ParIterable]

moors
Joined: 2010-10-06,
User offline. Last seen 36 weeks 4 days ago.
Re: Type classes and implicits

maybe I'm missing something, but GenericBased[Traversable] is not a subtype of GenericBased[Set]since GenericBased is covariant, when you need a value of type T <: GenericBased[Set] (e.g., the implicit argument for toGenericBasedWrapper's evidence parameter of type GenericBased[scala.collection.immutable.Set]), and that T looks like GenericBased[U] for some U, U will have to be a subtype of Set

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