Modules in Elixir

Define a module

A module is a named box for related functions. You open it with defmodule, add functions with def, and close the block with end. Module names start with a capital letter, which tells the compiler that the name is an atom with an Elixir prefix.

defmodule Math do def double(n) do n * 2 end def square(n) do n * n end end

Call the functions with the module name and a dot, as in Math.double(21), which returns 42. Every public function defined with def becomes part of the module interface.

Nest modules

A dot in a module name creates nesting, so Store.Item reads as the Item module inside Store. You can write the nesting with dots in one line or with a defmodule block inside another, and both spellings define the same full name.

defmodule Store do def welcome do "welcome" end defmodule Item do def price do 99 end end end

The full name of the inner module is Store.Item, so outside code calls Store.welcome() and Store.Item.price(). Nesting keeps related modules together without any extra syntax.

Alias long names

Long module names get noisy, so alias creates a short local nickname for a module used often in a file. After the alias line, the short name refers to the full dotted path.

defmodule Checkout do alias Store.Item def total(count) do Item.price() * count end end

Inside Checkout the name Item means Store.Item, which keeps the arithmetic line short. An alias only affects the module where it is written and never changes the original module.

Compile with elixirc

A module file needs no ceremony around it. Save the code in a file named math.ex, open a terminal in the same folder, and run the elixirc math.ex command. The compiler writes one beam file per module, and those beam files are what the virtual machine loads at runtime.

During study you can skip manual steps and let the elixir command compile files in memory before running them. Reach for elixirc directly when you want to check that a whole project compiles with no warnings.

Next: import, alias, require, use in Elixir

Article author: Arthur Isaev