How can I check if a protocol is implemented?

I wonder if there is a way to ask Elixir if this object implements this protocol, something like obj |> implements(Enumerable) ?

Basically, I have to distinguish between structures and maps. The solution I have right now looks 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, for example:

 cond do obj |> is_implemented(Enumerable) -> ... _ -> ... end 

Am I missing something? Is it possible to explicitly check whether the required protocol is implemented by an object?

+6
source share
1 answer

You can check if 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 
+8
source

All Articles