Search code examples
scalascala-collectionsscala-generics

Writing a function of some generic scala collection


I have defined a case class...

case class QueryRef[A](id: UUID, descriptor: (A) => Boolean, selector: immutable.Iterable[A] => A])

...that will be passed as a message between Akka Actors. The receiver will filter some collection of type A using the descriptor and then select a single element from the resulting filtered collection using the selector.

As written it will only work if the receiving actor's collection has type immutable.Seq[A]. I would like to generalize the above so that it would work with a generic collection of elements of type A. Is this possible?


Solution

  • Scala collections have a hierarchy, illustrated below. You just need to choose which level of the hierarchy is appropriate for your use-case. Iterable could be a good candidate for you if you want Maps and Sets to be allowed.

    Of course, you can then only use those functions which are available at that level of the hierarchy, you wouldn't be able to use any Seq specific functionality.

    enter image description here