apply

The BIF apply(Mod, Func, [Arg1, Arg2, ..., ArgN]) applies the function Func in the module Mod to the arguments Arg1, Arg2, ... ArgN. It is equivalent to calling this:

 
Mod:Func(Arg1, Arg2, ..., ArgN)

apply lets you call a function in a module, passing it arguments. What makes it different from calling the function directly is that the module name and/or the function name can be computed dynamically.

All the Erlang BIFs can also be called using apply by assuming that they belong to the module erlang. So, to build a dynamic call to a BIF, we might write the following:

 
1>​ apply(erlang, atom_to_list, [hello]).
 
"hello"

Warning: The use of apply should be avoided if possible. When the number of arguments to a function is known in advance, ...

Get Programming Erlang, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.