【发布时间】:2013-12-06 15:31:52
【问题描述】:
作为我previous question 的后续行动,我能否设计一个 隐式类来处理两种类型的SeqLike 扩展:
import collection.SeqLike
import collection.generic.CanBuildFrom
implicit class Test[A, Repr](val sq: SeqLike[A, Repr]) extends AnyVal {
// no constraints on Repr
def foo[B](f: A => B)(implicit ord: Ordering[B]): Repr = sq.sortBy(f)
// constraint that actually sq is Repr
def bar[B, To](fun: (A, A) => B)(implicit cbf: CanBuildFrom[Repr, B, To]): To = {
val b = cbf(sq) // NO!
// ...
b.result
}
}
bar 方法无法编译,因为我们缺少typeOf(sq) == Repr 的约束。正如其他人指出的那样,如果我将构造函数更改为 sq: Repr,我们将失去与类型 A 的连接。
现在,Repr 已断开连接。例如:
// in Test:
def isSortedBy[B](fun: A => B)(implicit ord: Ordering[B]): Boolean =
sq.sliding(2, 1).forall {
case a +: b +: _ => ord.lteq(fun(a), fun(b))
case _ => true // happens when it size == 1
}
[error] Test.scala: inferred type arguments [T,Equals] do not conform to method
unapply's type parameter bounds
[T,Coll <: scala.collection.SeqLike[T,Coll]]
[error] case a +: b +: _ => ord.lteq(fun(a), fun(b))
[error] ^
【问题讨论】:
-
我认为
self.sliding应该是sq.sliding对吧? -
@stew - 是的,抱歉,这是复制+粘贴的错误
标签: scala collections implicit-conversion