Sharing Values without Using Arguments
Learn about sharing values with functions without using arguments.
We'll cover the following...
Closures
We can share values with functions using closures. A closure has access to variable values both inside and outside of the code block. In Elixir, we can create an anonymous function and pass it a code block with the values of the variables defined outside it. It’s useful to share values with functions when we can’t control how the function is invoked because we can’t pass values to the function as parameters. We can’t control function calls, especially when we use functions that take other functions as arguments.
For example, we can use Elixir’s spawn to start a process and execute a function asynchronously. The spawn will invoke the given function asynchronously, and we can’t pass arguments to it. One way to share values with that function is by taking advantage of the closure:
iex> message = "Hello, World!"
iex> say_hello = fn ->
...