Map.get vs. Access - pros/cons?

The documentation says:

Keys in maps can be accessed through some of the functions in this module (such as Map.get/3 or Map.fetch/2) or through the map[] syntax provided by the Access module

Are there any pros/cons for using one over another? I mean especially in situations where the result would be the same. Also any performance / resource usage implications of using one over another?

1 Like

fetch/2will give you an error and say HEY THIS DOES NOT EXIST. Do something about it!

Map.fetch(medical_kit, :insulin_shot)
:error # CALL 911!

Map.get/2 is more chill and will be like hey uh I couldn’t find anything here’s nil - or give you a default. Like asking your wife for your Tom Ford sunglasses and honey if you can’t find it just grab me my Raybans no big deal.

Map.get(dresser, :tom_ford_sunglasses, :raybans)


Additionally, the Access syntax is also supported by Keyword List; so it allows for switching between Map en Keyword List without replacing calls.


I updated the question a bit to make it more explicit about what I ask about. I know the different usage possibilities. It is more about when I have a map and want to access existing/non-existing keys (without supplying own default to override the normally returned nil). IOW situations where Map.get and Access behave seemingly the same.

1 Like

map_or_kw[:something] || ”bananas" is Map.get/Keyword.get and is easier on the eye, imo.

Access lets you do nested gets, like map[:one][:two][:three]


Related fun fact:

iex(18)> nil[:access_works_for_nil]

Except map_or_kw[:something] || ”bananas" will behave differently on %{something: false} for example.