【发布时间】:2018-08-18 04:19:11
【问题描述】:
我正在使用 Scala 泛型和类型边界来了解其可能的用例。我对一个场景感到困惑。
假设我有一个 trait 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] 类型的表达式不符合预期类型 乙
【问题讨论】:
-
self reduce other首先是什么?reduce需要一个归约函数(A, A) => A,并返回一个A。self reduce other应该是什么意思,它怎么可能是Vector?我无法理解“到目前为止一切都很好” - 它还没有编译? -
对不起@AndreyTyukin,我尝试了太多东西,这就是我输入错误的原因,现在编辑。
self ++ other附加这两个GenTraversables。而且我不希望它返回 GenTraversable,而是返回 B。我希望我的意图现在很清楚。
标签: scala generics typeclass type-bounds f-bounded-polymorphism