silverdr
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/3orMap.fetch/2) or through themap[]syntax provided by theAccessmodule
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?
Most Liked
sergio
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)
marcandre
Except map_or_kw[:something] || ”bananas" will behave differently on %{something: false} for example.
BartOtten
Additionally, the Access syntax is also supported by Keyword List; so it allows for switching between Map en Keyword List without replacing calls.
cmo
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]
gregvaughn
Related fun fact:
iex(18)> nil[:access_works_for_nil]
nil







