scala f-bounded types explanation

前端 未结 2 1705
深忆病人
深忆病人 2020-12-03 15:27

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://twitt

相关标签:
2条回答
  • 2020-12-03 16:14

    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.

    0 讨论(0)
  • 2020-12-03 16:22

    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.

    0 讨论(0)
提交回复
热议问题