Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Elixir's nil implements Access behavior?

Tags:

elixir

As Elixir docs say:

...Access transparently ignores nil values:

iex> keywords = [a: 1, b: 2]
iex> keywords[:c][:unknown]
nil

This seems error-prone to me. I'd rather see nil[key] failing than returning nil.

I'm pretty sure there's a good reason why the language developers chose to go this route. What is that reason?

like image 776
DNNX Avatar asked Oct 31 '25 01:10

DNNX


1 Answers

nil does not implements an Access behaviour (nil is an atom FWIW.)

What happens there is: Access.fetch(nil, whatever) returns :error and get wraps :error to the default value passed to Access.get/3 as a third parameter.

The question “why” is better to address to José, the only idea I could come with is: that behaviour simplifies the code in case of deeply nested structures.

Also, this is a default behaviour for the first-level maps access:

iex> %{a: 42}[:b]
nil
like image 105
Aleksei Matiushkin Avatar answered Nov 02 '25 01:11

Aleksei Matiushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!