Question

No, this isn't a CanBuildFrom issue. I've defined a typeclass on a method but that method is not picking up for a List:

trait HeadLast[Elem, Coll]{
  def get(coll: Coll): (Elem, Elem)
}

class DoStuff[-T]{
  def stuff[C, TT <: T](coll: C, value: TT)(implicit hl: HeadLast[TT, C]) ={
    val (h, l) = hl get coll

    (h == value || l == value)
  }
}

object DoStuff{
  implicit def htrav[Elem, Repr <: TraversableLike[Elem, Repr]] = new HeadLast[Elem, Repr]{
    def get(coll: Repr) = (coll.head, coll.last)
  }
}

So, could it be an issue with variance? Is this just an implicit that won't be picked up and I need to specify one for each of List, Set, etc.?

Était-ce utile?

La solution

There is no problems in this code, but you should define htrav in HeadLast companion object or import it manually:

scala> (new DoStuff).stuff(List(1, 2, 3), 3)
<console>:11: error: could not find implicit value for parameter hl: HeadLast[Int,List[Int]]
              (new DoStuff).stuff(List(1, 2, 3), 3)
                                 ^

scala> import DoStuff._
import DoStuff._

scala> (new DoStuff).stuff(List(1, 2, 3), 3)
res0: Boolean = true

Compiler will not search in DoStuff object for this implicit HeadLast.

See also: Where does Scala look for implicits?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top