Scala Explanation of f-restricted types

After a few examples, I have to say that I do not understand what F-Bounded polymorphism brings.

To use an example from scala school ( https://twitter.imtqy.com/scala_school/advanced-types.html#fbounded )

They explain that they need some F-Bounded 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 understand what is the gain in using this type if you can use something like this:

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

Any explanation is appreciated.

thanks

+7
source share
2 answers

The advantage will 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 a pair for free, and you get the right type of return. Without this type, you must manually override each method that returns the same type (a lot of meaningless template), or you lose certainty in your types as soon as you call the non-overlapping method.

+4
source

In Scala, you can make your type parameters limited to type bindings. Here in the first method, you make your type parameter, creating an upper bound with a subclass of Container.

Using the 1st method, you cannot pass a parameter in the Container class, which is not a subclass of your Container class.

In your second example, you can pass an instance of the parameter type of any class. So, here you are not restricting anything, while in the first example you are restricting the type of a subtype of the Container class.

+1
source

Source: https://habr.com/ru/post/984414/


All Articles