Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "for" in "defimpl" in Elixir actually checks for?

Does "for" always checks the type of first argument in each function defined in a protocol?

EDIT (rephrasing): When protocol method has only one argument, implementation is found based on the type of this single argument (either direct or as Any). When protocol method has multiple arguments, which one is used to find the corresponding implementation? Is it always the first one? Can it be changed?

like image 847
Tomáš Brukner Avatar asked Dec 28 '14 16:12

Tomáš Brukner


1 Answers

The implementation is always determined based on the first argument.

When you define a protocol, a generic protocol module will be generated. All def clauses in that module will perform delegations to concrete functions, determining which function to call based on the type of the first argument.

The place in Elixir source where this happens is here (where first argument is explicitly referred to as t), and here (where t is passed to impl_for! to obtain the module where the function call is forwarded).

A defimpl will generate concrete modules whose names adhere to the internal conventions used by defprotocol. Thus it is ensured that function call will be delegated to the proper concrete module.

like image 191
sasajuric Avatar answered Sep 29 '22 15:09

sasajuric