Skip to content

Commit c22c907

Browse files
committed
Add Protocol.impl_for/1 and Protocol.impl_for!/1
1 parent 83a70d7 commit c22c907

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

lib/elixir/lib/protocol.ex

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,49 @@ defmodule Protocol do
307307
raise ArgumentError, "invalid arguments for def inside defprotocol"
308308
end
309309

310+
@doc """
311+
Returns the implementation of a given protocol for a given data type
312+
or `nil`.
313+
314+
This wraps `protocol.impl_for(value)` with a generic type signature.
315+
316+
## Examples
317+
318+
iex> Protocol.impl_for(Enumerable, [1, 2, 3])
319+
Enumerable.List
320+
321+
iex> Protocol.impl_for(Enumerable, :atom)
322+
nil
323+
"""
324+
@doc since: "1.19.0"
325+
def impl_for(protocol, value) do
326+
protocol.impl_for(value)
327+
end
328+
329+
@doc """
330+
Returns the implementation of a given protocol for a given data type
331+
or raises.
332+
333+
This wraps `protocol.impl_for!(value)` with a generic type signature.
334+
335+
## Examples
336+
337+
iex> Protocol.impl_for!(Enumerable, [1, 2, 3])
338+
Enumerable.List
339+
340+
iex> try do
341+
...> Protocol.impl_for!(Enumerable, :atom)
342+
...> rescue
343+
...> Protocol.UndefinedError -> :raised
344+
...> end
345+
:raised
346+
347+
"""
348+
@doc since: "1.19.0"
349+
def impl_for!(protocol, value) do
350+
protocol.impl_for!(value)
351+
end
352+
310353
@doc """
311354
Checks if the given module is loaded and is protocol.
312355

0 commit comments

Comments
 (0)