Explanation for why we have [B >: A] in scala's List.sum[B >: A]

Let's understand

def sum[B >: A](implicit num: Numeric[B]): B = foldLeft(num.zero)(num.plus)

1. What is B >: A why is it needed?

2. Why implicit?
3. What is this num?


scala's List.sum method uses foldLeft in order to perform its addition.
foldLeft function takes two arguments:

1. the zero value
2. the function which knows to append two elements

so fold left starts with zero and then uses the given function to append the items.

so far allright?

Now, as we pass in a function to foldLeft, it needs to operate on the actual items in the List.  The actual items of the list are defined (see List definition) as A that means that the function need to be able to run methods defined on type A.

So this function will accept two items from List current sum and an item from List A and run on them.

imagine what would happen if num.plus function would accept subtypes of A, we don't know what this function does internally we are only aware of its signature, as its signature would say num.plus accepts subtypes of A we cannot trust that it would run methods not defined on A methods which are defined only on subtypes of A.  So we want our num.plus to accept only A's or supertypes of A's and thats what it accepts.

implicit num: Numeric[B]

is defined as accepting B >: A this means num works on supertypes of A which is what we want we are assured any method this function will work on exists also on A's.


Comments