BasilTomato
BasilTomato

Reputation: 1071

How do I choose the collection type to return in Scala?

In case of Set or List, the choice seems to be easier, but what do I do for Java's Collection, Iterable equivalent? Do I go for Seq? Traversable? GenTraversableOnce?

Upvotes: 2

Views: 265

Answers (2)

Nami
Nami

Reputation: 1235

You need to decide based on your need. For example: According to Scala Documentation the definition of Seq is

Sequences are special cases of iterable collections of class Iterable. Unlike iterables, sequences always have a defined order of elements. Sequences provide a method apply for indexing.

So if you want to benefit ordering or you want to retrieve element by index you can use Seq

Again according to Scala Documentation if you are mainly interested in iteration over your Collection Traversable is sufficient

Just notice that there is a general good practice that for your function signature like function return type, use more general (abstract) data type to prevent unnecessary performance penalty for the function callers.

Upvotes: 4

Sebastiaan van den Broek
Sebastiaan van den Broek

Reputation: 6351

As often, it will depend on the needs of your caller. Traversable is pretty high level (you only get foreach) but it might be sufficient. Seq would be used if you need a defined order of elements. GenTraversableOnce would be a bit abstract for me and possibly for your fellow coders.

Upvotes: 3

Related Questions