【问题标题】:Scala upper type boundScala 类型上限
【发布时间】:2015-06-26 04:45:20
【问题描述】:
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 提供方法距离。 我想在seq[B] 上使用函数findNN,在C 类中有一个中心。 distance 应该可以工作,因为它可以在 A 上工作

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

【问题讨论】:

  • 你举了一个奇怪的例子。类型参数 T 永远不会在您的 testF 函数中使用。 def testF[T &lt;: P](list: List[T]): List[T] = list 将工作,如果你这样做 testF(List(new P("a"))
  • 好吧,我整理了一下脑袋,写了一个我认为反映当前设置的玩具示例。
  • r 函数再次有一个未使用的类型参数O。如果从未使用过类型,则不能限制函数中的类型。
  • 暂时忽略上限,写def foo[A]: List[A] = List("bar") 之类的东西也无法编译。
  • @PeterNeyens:你觉得findNN这个功能能用吗?同时我正在重构我的代码..

标签: scala types type-bounds


【解决方案1】:

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

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

【讨论】:

  • 不。我希望这对于P 的超类型失败。让我想一个更好的例子。
  • 所以你需要“P 或任何不是 P 子类的类”?你能举个例子,你需要这个吗?
【解决方案2】:

您正在尝试使用类型参数 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")

【讨论】:

    猜你喜欢
    • 2011-11-15
    • 2018-03-19
    • 2015-10-15
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多