Reducing collection to something else than a super-type of the element

Looking at Vectior#reduce we see that the resulting type must be a super-type of the element type.

Is there an operation that allows producing any type?

you can use foldLeft foldRight or fold depending on your use case. For example


Reduce takes the elements, and uses a function to reduce any two elements to one, until you have one element left.

That means you must produce an element of the same type, because it’s used for the next reduction step.

If you want to produce a different type, you need a function that takes a different type as one of the arguments too. That also means you have to pass one in to start that all off.

That method is called fold, and there is a variety that “starts” left, and one that “starts” rigtht, called foldLeft and foldRight. They take two argument list, for a start value of the result type, and for a function combining a value of the result type and one of the element type into a value of the return type.

1 Like