The return value

Hi all
In the functional world, at end of the function it always expects something to return.

For example, take a look at macro ExUnit the setup all macro.

In the example you can see in the setup all macro it will return an atom.

What is the return value, if I have a function does not return nothing(for example an empty function)?

Thanks

iex(1)> defmodule Foo do
...(1)> def foo do
...(1)> end
...(1)> end
{:module, Foo,
 <<70, 79, 82, 49, 0, 0, 4, 116, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 126,
   131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115,
   95, 118, 49, 108, 0, 0, 0, 4, 104, 2, ...>>, {:foo, 0}}
iex(2)> Foo.foo
nil
3 Likes

What you would call “an empty function” in Elixir returns the nil value.

For instance, let’s take a look at the following code:

defmodule Test do
  def test1 do
  end
end

And once loaded in IEx:

Erlang/OTP 19 [erts-8.0] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]

Interactive Elixir (1.3.2) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> Test.test1
nil
1 Like

What should I return in your case?

I just experimented around and I believe it returns nil :slight_smile:

1 Like

honestly if you really have nothing to return, then just don’t return anything. But returning an :ok atom in case of success is often considered good practice, so people can pattern-match on it and it can change to :error in case of failure.

2 Likes