fireproofsocks
Why keyword lists for opts instead of maps?
I’m sure this has been asked elsewhere (but forgive me I could not find something that addressed this specifically)…
Why do Elixir functions usually take keyword lists as options? Why not maps? Keyword lists are problematic especially if you’d like to pattern match on a map key to route to different functions, for example. Is there a historical or performance-based reason why keywords are used over maps?
Most Liked
josevalim
Elixir had an option to choose either keyword lists and maps for options. The reason why we chose keyword lists are because they preserve user ordering and they allow duplicate keys. We use both features in Elixir itself.
For example, in try/catch/after, we warn if you put after before catch, as that would read weird. Using maps would not allow us to warn in those cases, as you always have alphabetical ordering.
When you do import Keyword, only: [get: 2, get: 3], those are duplicate keys. Keyword.__info__(:functions) returns duplicate keys too.
In other words, there are scenarios where keyword lists can be useful and unifying opts under keyword lists is reasonable. Community projects, such as Ecto, leverages them too. Plus other benefits such as Erlang compat.
gregvaughn
Keyword lists are very core to the Elixir syntax itself. For example
def the_answer do
42
end
is syntax sugar for
def the_answer, do: 42
or even
def(the_answer, [do: 42])
which is basically 2 parameters passed to the def macro. The last one is a keyword list with a :do key in it.
This is why all your functions can take a keyword list without square braces as the last parameter – because the core language syntax uses that.
christhekeele
This is worth highlighting, it gives you a CLI-repeated-flag-like interface for options.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









