Question

I want to store a number of participants for a meeting. The order of them is not important. The only thing I want to make sure is, that I will be able to add and remove participants, use filter functions (and alike) and get their number. Also duplicates are not allowed. I started using List for the method signature, but now I wonder if I should accept a more abstract type. I saw types like Traversable, TraversableLike, Iterable and IterableLike.

The number of participants will be rather low, usually below 100. Changes will be made occasionally. The participants are immutable (but they have mutable properties e.g. a List of actions they performed for that meeting).

What would be the appropriate abstraction level for my case?

Was it helpful?

Solution

You mentioned in your comments that your requirements include that:

  • A) You must be able to add and remove elements from the collection.
  • B) The order of the elements is not important.
  • C) Duplicate entries are not allowed.

I would suggest using an immutable Set. It should have effectively constant time additions, removals, and lookups, and will automatically prevent the addition of duplicates. This is probably a better fit than a List, which in Scala requires linear time to update, append to, or lookup in, as it is singly linked and can only be accessed starting from the head.

The syntax for adding and removing from an immutable set is fairly nice as well.

val xs = Set(alice, bob)
val xs2 = xs + carl              // Set(alice, bob, carl)
val xs3 = xs2 -- Set(alice, bob) // Set(carl)

You also get all your typical set operations, like unions, intersects, etc.

As with anything, if you have a large enough set of data that performance really matters, benchmark your results.

Reference: Performance Characteristcs of Scala Collections

OTHER TIPS

Scala has a lot of collection types that are pretty much only there to allow clever optimizations in the implementation (see Is the scala 2.8 collections library a case of the longest suicide note in history?). The ones you actually want to use only have an [A] and nothing else, and generally don't have suffixes like "Like."

If you want something more abstract than a List, try a Seq if you need to index by a number, an Iterable for when you need to create an iterator or take elements from the right, and a Traversable if you don't.

However, generally you would use a concrete type for "internal" storage, where you would be adding and removing elements. In those cases, you select one based on its performance characteristics, for which a List is most likely just fine in your case. The more abstract types are more for accepting a collection from other code.

Licensed under: CC-BY-SA with attribution
scroll top