Trap Of `Map.update/4`

1 minute read

If we want to update a value in a map of which key we can not ensure it's exist. We can get the two way quickly:

1 record = Map.get(map, key, [])
2 Map.put(map, key, [new | record])

Or we can use `Map.update/4`:

1 Map.update(map, key, [], fn record -> [new | record] end)

They are look like as the same completely. But the result is different, the result by `Map.update/4` of above code is just get the last put in value. It will only be empty or one item in the list.

Reason

In `Map.update/4`, if the key not exist, will just return the default value you set. So you can not get the updated value like `acc`.

The version correctly:

1 Map.update(map, key, [new], fn record -> [new | record] end)