我们希望在列表上调用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 ...
答案 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。您会发现List
,Seq
和许多(并非所有)继承或混合Traversable
的人都是SeqLike
实现的。