I would like to sort-of-add a new value to an immutable Map. Whereas the normal + function replaces the old key/value pair with the new one, what I’d like to do is add the new key/value pair if the key is not already in the Map, however, if they key is already there, I’d like to merge the old value with the new value according to a given merging function.
I have two questions about doing this.
Q1) isn’t there a function I can use for this? Or do I have to write it myself?
Here is the function I’ve written
Ahh, but it is only a regular tuple in some limited circumstances. For example (K -> V) is not the same as (K,V) when K and V are type names. And also, case (k -> v) is not the same as case (k,v) in a pattern match.
To expand on my previous message, it seemed inconsistent to me too so I fixed that. However not everyone liked the type syntax, so writing K -> V as a type is still not possible. You can easily add such a type alias to your own code though.
Arguably so, but the key insight is that (k -> v) isn’t syntax. Instead, -> is just a plain old function that returns a Tuple2. So (in Scala 2.12), you can only use it in function-like ways.
I assume that @Jasper-M added the necessary unapply() bits to make it work in pattern matches for 2.13, but that’s still not magic: it’s still not a type, just a bit of pretty sugar (in the stdlib, not the language) that you can use as special syntax to assemble and disassemble tuples…
FWIW, you can define both in very few lines in your own code.
In 2.13 you just need to add type ->[K,V] = (K,V) to be able to use -> as a type.
In 2.12, you’ll additionaly need the extractor for pattern matches: