Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check whether the protocol is implemented?

Tags:

elixir

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?

like image 390
Aleksei Matiushkin Avatar asked Sep 21 '16 06:09

Aleksei Matiushkin


1 Answers

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
like image 70
Dogbert Avatar answered Oct 22 '22 17:10

Dogbert