scala, guidelines on return type - when prefer seq, iterable, traversable

后端 未结 5 1100
天命终不由人
天命终不由人 2021-01-31 07:44

When do you choose to type a given function\'s return type as Seq vs Iterable vs Traversable (or alternatively even deeper within Se

5条回答
  •  攒了一身酷
    2021-01-31 07:57

    A rule of thumb I follow is, depending on implementation, to make the return types as specific as possible and the types of arguments as general as possible. It's an easy to follow rule and it provides you with consistent guarantees on the type properties with maximum freedom.

    Say, if you have a function implementation which just traverses a data structure with methods like map, filter or fold - those that are implemented in the trait Traversable, you can expect it to perform equally on any type of input collection - be it a List, Vector, HashSet or even a HashMap, so your input argument should be specified as Traversable[T]. The choice of output type of the function should only depend on its implementation: in this case it should be Traversable too. If however in your function you force this data structure to some more specific type with methods like toList, toSeq or toSet, you should specify the appropriate type. Notice the consistency between the implementation and the return type?

    If your function accesses the elements of input by index, the input should be specified as IndexedSeq, as it is the most general type that provides you with guarantees on effective implementation of method apply.

    In case of abstract members the same rule applies with the only difference that you should specify the return types based on how you plan to use them instead of implementation, thus most often they will be more general than in implementation. The categorical choices Seq, Set or Map are the most expected.

    Following this rule you protect yourself from very common cases of bottleneck when, for instance, items get appended to List or contains gets called on a Seq instead of a Set, yet your program remains a nice degree of freedom and is consistent in sense of choice of types.

提交回复
热议问题