0
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}
  }

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

超类A提供方法距离。我想在类中使用findNNseq[B]功能Cdistance应该有效,因为它适用于A

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

4

2 回答 2

2

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

class P(name: String)
class E(_name: String, role: String) extends P(_name)
def testF[T >: P](): List[T] = List(new P("Henry"))
于 2015-06-25T17:09:30.197 回答
1

您正在尝试使用类型参数R(具有上限 type 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")
于 2015-06-25T20:45:20.433 回答