Using import for macros

In the Elixir programming book, there this code example showing how to overload arithmetic operators:

defmodule Operators do
  defmacro a + b do
   quote do
     to_string(unquote(a)) <> to_string(unquote(b))
   end
  end
end

defmodule Test do
  IO.puts(123 + 456)
  import Kernel, except: [+: 2]
  import Operators
  IO.puts(123 + 456)
end

IO.puts(123 + 456)

According to the Elixir documentation “Public functions in modules are globally available, but in order to use macros, you need to opt-in by requiring the module they are defined in.”.

Why in this case is the module Operators imported, not required?

Its because importing a module automatically requires it.

More info: https://elixir-lang.org/getting-started/alias-require-and-import.html#import

2 Likes