When do you choose to type a given function\'s return type as Seq
vs Iterable
vs Traversable
(or alternatively even deeper within Se
This is a good question. You have to balance two concerns:
Where (1) asks you to be as little specific about the type (e.g. Iterable
over Seq
), and (2) asks you the opposite.
Even if the return type is just Iterable
, you can still return let's say a Vector
, so if the caller wishes to gain extra power, it can just call .toSeq
or .toIndexedSeq
on it, and that operation is cheap for a Vector
.
As a measure of the balance, I would add a third point:
Seq
. If you can assume that no two equal objects can occur, give a Set
. Etc.Here are my rules of thumb:
Set
, Map
, Seq
, IndexedSeq
List
in favour of Seq
. It allows the caller to do pattern matching with the cons extractorscollection.immutable.Set
, collection.immutable.IndexedSeq
)Vector
), but the general type (IndexedSeq
) which gives the same APIIterator
instances, the caller can then easily generate a strict structure, e.g. by calling toList
on itIndexedSeq
Of course, this is my personal choice, but I hope it sounds sane.