Kernel.defmodule
defmodule
, go back to Kernel module for more information.
Defines a module given by name with the given contents.
This macro defines a module with the given alias
as its name and with the
given contents. It returns a tuple with four elements:
:module
- the module name
- the binary contents of the module
- the result of evaluating the contents block
Examples
defmodule Number do
def one, do: 1
def two, do: 2
end
#=> {:module, Number, <<70, 79, 82, ...>>, {:two, 0}}
Number.one()
#=> 1
Number.two()
#=> 2
Nesting
Nesting a module inside another module affects the name of the nested module:
defmodule Foo do
defmodule Bar do
end
end
In the example above, two modules - Foo
and Foo.Bar
- are created.
When nesting, Elixir automatically creates an alias to the inner module,
allowing the second module Foo.Bar
to be accessed as Bar
in the same
lexical scope where it's defined (the Foo
module). This only happens
if the nested module is defined via an alias.
If the Foo.Bar
module is moved somewhere else, the references to Bar
in
the Foo
module need to be updated to the fully-qualified name (Foo.Bar
) or
an alias has to be explicitly set in the Foo
module with the help of
Kernel.SpecialForms.alias/2
.
defmodule Foo.Bar do
# code
end
defmodule Foo do
alias Foo.Bar
# code here can refer to "Foo.Bar" as just "Bar"
end
Dynamic names
Elixir module names can be dynamically generated. This is very useful when working with macros. For instance, one could write:
defmodule String.to_atom("Foo#{1}") do
# contents ...
end
Elixir will accept any module name as long as the expression passed as the
first argument to defmodule/2
evaluates to an atom.
Note that, when a dynamic name is used, Elixir won't nest the name under
the current module nor automatically set up an alias.
Reserved module names
If you attempt to define a module that already exists, you will get a warning saying that a module has been redefined.
There are some modules that Elixir does not currently implement but it may be implement in the future. Those modules are reserved and defining them will result in a compilation error:
defmodule Any do
# code
end
** (CompileError) iex:1: module Any is reserved and cannot be defined
Elixir reserves the following module names: Elixir
, Any
, BitString
,
PID
, and Reference
.