使用TraversableLike定义的类型类不适用于List

时间:2013-12-23 16:53:03

标签: scala typeclass implicit

不,这不是CanBuildFrom问题。我已经在方法上定义了一个类型类,但该方法没有为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)
  }
}

那么,这可能是一个方差问题吗?这只是隐含的,不会被提取,我需要为ListSet等每个指定一个吗?

1 个答案:

答案 0 :(得分:3)

此代码中没有问题,但您应在htrav随播广告对象中定义HeadLast或手动导入:

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

编译器不会在DoStuff对象中搜索此隐式HeadLast

另请参阅:Where does Scala look for implicits?