我正在使用 scala 泛型和类型边界来了解其可能的用例。我对一个场景感到困惑。
假设我有一个特质 Combinable
trait Combinable[T] {
def combine(other: T): T
}
我想为 Vector[A] 实现一个隐式定义:
implicit def vectorCombinable[A](self: Vector[A]) = new Combinable[Vector[A]] { // note: using scala 2.11, no SAM support
override def combine(other: Vector[A]): Vector[A] = self ++ other
}
到目前为止一切都很好,如果我将 Vector 替换为 B 类型上限,问题就开始了GenTraversable
:
implicit def vectorCombinable[A, B <: GenTraversable[A]](self: B): Combinable[B] = new Combinable[B] {
override def combine(other: B): B = self ++ other
}
我只是希望此方法以 B 类型返回,但self ++ other
失败并出现以下编译错误:
GenTraversable[A] 类型的表达式不符合预期的 B 类型