Functions
8 min · Elixir
Package code under a name inside a module.
Enemy 1 of 5
Defining and calling a function
In Elixir, named functions can't float around on their own — every named function lives inside a module, a named container that groups related functions together. `defmodule Main do ... end` opens a module named `Main`; inside it, `def name(params), do: body` defines a function. This grouping isn't just organizational ceremony: modules are also how Elixir looks up and dispatches to the right function when you write `Main.double(5)`.
This is a fairly common pattern across languages that separate "free-floating scripts" from "named, reusable functions" — Java and Scala require a class or object for the same reason, for instance. The payoff is that once your program grows, related functions stay grouped and namespaced instead of colliding with similarly-named functions elsewhere.
`def double(n), do: n * 2` is the compact one-line form: no explicit type annotations (Elixir doesn't require declaring parameter or return types — it's dynamically typed, so types are checked at runtime rather than compile time), and the `, do: expression` syntax puts a single-expression body right on the same line as the `def`. For longer bodies you'd use the block form: `def double(n) do ... end`.
Whatever the *last* expression in the function body evaluates to is automatically returned — there's no separate `return` keyword in Elixir at all. Calling a function defined inside a module requires the module prefix: `Main.double(5)`, not just `double(5)` from outside the module.
Loading editor...