Various methods on Maps end up returning a Iterable collection over key value pairs.
Handling these in Scala can sometimes seem a bit verbose or opaque, with my understanding that the choices seemingly being either a pair match, or using ._1
and ._2
.
E.g. groupMapReduce(_._1)(_._2)(_ + _)
or
groupMapReduce{ case (k, v) => k}{ case (k, v) => v}(_ + _)
I was wondering whether it would be helpful to have “key
” and “value
” methods added to Tuple2 as aliases for _1 and _2.
E.g., so the code above could be written as:
groupMapReduce(_.key)(_.value)(_ + _)
In Scala 3, we wouldn’t need the case keyword so the first code example would be shorter. Of course, there is also the choice that these could be added as extension methods, but really my question is whether it would be beneficial for these to be added to the standard library.
While in your example they look good, not all tuples are key-value pairs. Thus, in other contexts, they could be confusing.
Also, I personally try not to use tuples that much but rather case classes that properly represent the data.
Usually, when I have tuples, they are on small scopes, like a chain of calls on a collection which could end in something similar to your example. Where, IMHO, the extra clarity of the names is not that big since I can see in the previous line what was on the tuple.
3 Likes
Thanks for the comments.
I agree that not all tuples are key value pairs, but the descriptions for key and value could make that clear.
I agree that using case classes make sense, but the standard APIs don’t generate then, e.g. if you iterate a map then you get an iteration of pairs …
Regarding the clarity, I partly agree, and for someone who is familiar with Scala it is okay. But if I was to give that program to someone else, then having explicit names like key and value are likely to make the code more readable.
As tuples are going to be represented as an HList
in Scala 3, what are the possibilities for evolving further to something like LabelledGeneric
?
This would allow the fields in a tuple to have names appropriate to their context (whatever that context happened to be).
1 Like