I wonder if there any way to ask Elixir whether this object implements that protocol, something like obj |> implements(Enumerable)
?
Basically, I have to distinguish structs and maps. The solution I currently have is kinda ugly:
try
obj |> Enum.each ...
rescue
e in Protocol.UndefinedError -> obj |> Maps.keys ...
end
The above works, but I would prefer to use pattern matching like:
cond do
obj |> is_implemented(Enumerable) -> ...
_ -> ...
end
Am I missing something? Can one explicitly check whether the desired protocol is implemented by the object?
You can check whether Protocol.impl_for(term)
returns nil or not:
iex(1)> Enumerable.impl_for []
Enumerable.List
iex(2)> Enumerable.impl_for {}
nil
iex(3)> Enumerable.impl_for MapSet.new
Enumerable.MapSet
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With