質問

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.?

役に立ちましたか?

解決

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?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top