Or how to avoid accidental removal of duplicates when mapping a Set
?
This is a mistake I'm doing very often. Look at the following code:
def countSubelements[A](sl: Set[List[A]]): Int = sl.map(_.size).sum
The function shall count the accumulated size of all the contained lists. The problem is that after mapping the lists to their lengths, the result is still a Set
and all lists of size 1 are reduced to a single representative.
Is it just me having this problem? Is there something I can do to prevent this happening? I think I'd love to have two methods mapToSet
and mapToSeq
for Set
. But there is no way to enforce this, and sometimes you don't locally notice that you are working with a Set
.
Maybe it's even possible that you were writing code for a Seq
and something changes in another class and the underlying object becomes a Set
?
Maybe something like a best practise to not let this situation arise at all?
Remote edits break my code
Imagine the following situation:
val totalEdges = graph.nodes.map(_.getEdges).map(_.size).sum / 2
You fetch a collection of Node
objects from a graph, use them to get their adjacent edges and sum over them. This works if graph.nodes
returns a Seq
.
And it breaks if someone decides to make Graph
return its nodes as a Set
; without this code looking suspicious (at least not to me, do you expect every collection could possibly end up being a Set
?) and without touching it.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…