Circular addiction in Scala collections

Trait Traversable has methods like toList , toMap , ToSeq . Given that List , Map , Seq are subclasses of Traversable , this creates a circular dependency, which is usually not a desirable design pattern.

I understand that this is limited to the collection library and provides some interesting conversion methods.

Has an alternative design been considered? For example, a utility class or adding conversion methods to Predef ?

Let's say I want to add a new class: class RandomList extends List {...} . It would be nice to have a toRandomList method for all Traversable classes, but for this I would have to β€œpimp my library” implicitly on Traversable? This seems a little redundant. With the utility class design, I could simply extend this class (or Predef) to add my conversion method. What will be the recommended design here?

+4
source share
4 answers

An alternative and extensible approach would be to[List] , to[RandomList] .

It's a little tricky to add this with implicits. https://gist.github.com/445874/2a4b0bb0bde29485fec1ad1a5bbf968df80f2905

+7
source

To add toRandomClass , you have to resort to the style of my library. However, why do you think this is too much? Overhead is negligible. And this will not work, expanding the utility class - why does Scala look into your new class for this method? Not to mention the fact that you need to create an instance of such a class in order to have access to its methods.

+5
source

There is no circular dependence. Circular dependence is what happens when there are several independent components that relate to each other. The Scala standard library is one of the components. Since it is always built in one step, there are no problems.

+5
source

You're right. Let me remove toString from the String class ...

+4
source

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


All Articles