scala f-bound类型解释

jer*_*mie 7 polymorphism types scala f-bounded-polymorphism

经过几个例子后,我不得不说,我不明白F-Bounded多态带来了什么.

使用scala学校的示例(https://twitter.github.io/scala_school/advanced-types.html#fbounded)

他们解释说他们需要一些F-Bounded类型,以便子类可以返回子类型.所以他们做这样的事情:

trait Container[A <: Container[A]] extends Ordered[A]
class MyContainer extends Container[MyContainer] {
  def compare(that: MyContainer) = 0
}
Run Code Online (Sandbox Code Playgroud)

但是当我可以使用这样的东西时,我看不出使用这种类型有什么好处:

trait Container[A] extends Ordered[A]
class MyContainer extends Container[MyContainer] {
  def compare(other: MyContainer) = 0
}
Run Code Online (Sandbox Code Playgroud)

任何解释都非常欢迎

谢谢

Rex*_*err 5

当看起来像这样时,优势就会显现出来:

trait Container[A <: Container[A]] extends Ordered[A] {
  def clone: A
  def pair: (A, A) = (clone, clone)
}

class MyContainer extends Container[MyContainer] {
  def clone = new MyContainer
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以pair免费获得,并获得正确的返回类型。没有这样的事情,您必须手动覆盖返回相同类型的每个方法(很多无意义的样板),否则,一旦调用非覆盖方法,您就失去类型的特异性。