scala f-bounded types explanation

限于喜欢 提交于 2019-11-26 17:49:29

问题


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

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

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
}

Any explanation is very welcomed

Thanks


回答1:


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
}

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.




回答2:


In Scala you can make your type parameters constrained by a type bound. Here in your first method you are making your type parameter making upper bound with sub class of Container.

By using your 1st method you can't pass parameter in Container class which is not sub class of your Container class.

In your 2nd example you can pass parameter type instance of any class. So here your are not restricting anything while in 1st example you are restricting type sub type of Container class.



来源:https://stackoverflow.com/questions/29339548/scala-f-bounded-types-explanation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!