Scala 上限类型

Scala upper type bound

class P(name: String)
class E(_name: String, role: String) extends P(_name)

def testF[T <: P](x: List[T]): List[T] = x

val le = List(new E("Henry", "Boss"))
class Test[R <: E](l: List[R]) {
  def r[O <: P] (): List[O] = testF(l)
}

我得到:

Error:(8, 38) type mismatch;
 found   : List[R]
 required: List[O]
  def r[O <: P] (): List[O] = testF(l)

我的直觉表明这应该有效,因为 T 的类型上限比 O 更严格。

**** 编辑 ****

  def findNN[A, B <: A, C <: A, T] (seq: Seq[B], n: Int, center: C, distance: (A, A) => T)
  (implicit ord: Ordering[T]): Seq[B] = {
    import ord._
    val ds = seq map ( (a: A) => distance(a, center))
    val uds = ds.distinct
    //#TODO: replace quickSelect with median-of algorithm if necessary
    val kel = quickSelect(uds, n)
    val z = seq zip ds
    val (left, _) = z partition Function.tupled((_, d: T) => d <= kel)
    left map {t => t._1}
  }

好的,让我们看看上面的例子。

superclass A提供方法距离。 我想在 seq[B] 上使用函数 findNN,中心在 class C 中。 distance 应该有效,因为它适用于 A

根据提供的反馈,无法简化上述类型签名。

你打错了,你需要 >: 而不是 :<

class P(name: String)
class E(_name: String, role: String) extends P(_name)
def testF[T >: P](): List[T] = List(new P("Henry"))

您正在尝试使用类型参数 R(具有上限类型 E)限制结果的类型,而您没有使用类型 R你的功能。

正确使用类型参数(带上限)的示例:

def testF[T <: P](list: List[T]): List[T] = list

testF(List(new P("Tom"))) 
// List[P] = List(P@43bc21f0)
testF(List(new E("Jerry", "Mouse")))
// List[E] = List(E@341c1e65)

类型参数的错误使用:

// does not compile, what is A ??
def foo[A]: List[A] = List("bar")