Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

How can I check whether the protocol is implemented?

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?

Upvotes: 16

Views: 2934

Answers (1)

Dogbert
Dogbert

Reputation: 222168

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

Upvotes: 24

Related Questions