通过implicits定制Scala序列的高阶函数?

时间:2014-02-26 13:57:52

标签: scala

我们希望在列表上调用List时,在Seq上调用Seq。

implicit class SeqWithMyFilter[+T](seq: Seq[T]) {
  def myFilter(pred: T => Boolean): Seq[T] = seq.filter(pred)
}

scala> List("x").myFilter(_=="x")
res1: Seq[String] = List(x)

但添加类型不会编译:

implicit class SeqWithMyFilter[+T, +U <: Seq[T]](seq: U) {
  def myFilter(pred: T => Boolean): U = seq.filter(pred)
}

...因为seq.filter(pred)总是返回Seq ...

1 个答案:

答案 0 :(得分:1)

您要做的是使用SeqLike,以便:

implicit class SeqWithMyFilter[A, Repr <: SeqLike[A, Repr]](seq: Repr){
  def myFilter(pred: A => Boolean): Repr = seq filter pred
}

因为filter的定义是根据实现类定义的:

abstract def filter(pred: T => Boolean): Repr

看看TraversableLike。您会发现ListSeq和许多(并非所有)继承或混合Traversable的人都是SeqLike实现的。