Function name in Parentheses

A colleague of mine found out that you can define functions with their function name in parentheses and Elixir will create a function with arity 0 out of it. An example:

defmodule A do
    def (foo) do
        IO.inspect("called")
        :bar
    end
end

iex> A.foo()
"called"
:bar

iex> A.__info__(:functions)
[foo: 0]

I’ve never seen this syntax. Can somebody explain why and how this works, please?

def is a macro

you can even do:

def(foo(a,b), do: a + b)

if you want

4 Likes

And also you can

foo(a, b) |> def do
  a + b
end

:smiley:
learned that from Cursed Elixir

8 Likes

Oh wow :smile: That’s interesting! Thanks a lot!

Don’t do these things. I think the only place where it’s remotely useful is if for some reason you need to assign a function a name that isn’t a “normal atom” (like strange characters, or spaces). At its core,this is how “test” names work.