Passing in options: Maps vs. Keyword lists

There are situations where the latter two properties are very handy. Ecto’s query syntax and Elixir’s OptionParser are situations where you need both. The import special form also leverages the last property (keys can be given more than once). I am pretty sure there are more examples but those are three from the top of my mind.

One of the reasons I also like to use keywords list for options is because we have a well defined dichotomy where keyword lists are used for incomplete sets (you do not need to pass all keys) while maps expect all keys to be there. This allows me to use the assertive map.key syntax when using maps. It doesn’t need to be an OR choice though. I agree pattern matching on maps is really handy and for such cases I would likely accept a keyword list but convert it to a map with defaults:

map = Enum.into(user_options, %{key: "default", other_key: false, ...})

This way the API is consistent with Elixir and you can still leverage the map properties when you don’t care about duplicates nor ordering.

24 Likes