- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Type classes and implicits
Thu, 2012-01-26, 11:33
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]
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