scala f 有界类型解释 [英] scala f-bounded types explanation

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

问题描述

看了几个例子,我不得不说,我无法理解F-Bounded多态带来了什么.

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-Bounded 类型,以便子类可以返回子类型.所以他们做这样的事情:

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
}

非常欢迎任何解释

谢谢

推荐答案

当它看起来像这样时,优势就来了:

The advantage would come when it looks something like this:

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天全站免登陆