Scala F边界类型说明 [英] scala f-bounded types explanation

查看:108
本文介绍了Scala F边界类型说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过几个例子,我不得不说,我不明白F界多态带来的东西.

After going through a few examples, I have to say, I fail to understand what the F-Bounded polymorphic brings.

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

To use the example from scala school (https://twitter.github.io/scala_school/advanced-types.html#fbounded)

他们解释说,他们需要一些F边界类型,以便子类可以返回子类型. 因此,他们会执行以下操作:

They explain that they need some F-Bounded type so that the subclass can return the subtype. So they do something like this:

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

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

But I don't see what is the gain of using this kind of type when you could use something like this:

trait Container[A] extends Ordered[A]
class MyContainer extends Container[MyContainer] {
  def compare(other: MyContainer) = 0
}

任何解释都非常受欢迎

谢谢

推荐答案

优点如下:

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
}

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

Now you get pair for free, and you get the correct return type. Without something like this you must manually override every single method that returns the same type (lots of pointless boilerplate), or you lose specificity in your types as soon as you call a non-overridden method.

这篇关于Scala F边界类型说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆