Imports in Elixir

Published October 06, 2018 by Toran Billups

In part 12 of my Elixir journey I'll explore how imports work in the language.

Import

Normally I prefix a function name with the module name like you see below with `Enum.map`.

    defmodule Demo do
      def transform(list) do
        Enum.map(list, &(&1 + 1))
      end
    end
  

But if you find yourself using a handful of functions from the same module, or even repeating the same module + function name multiple times you can `import` the specific function(s) you need by name and arity (the number of arguments expected by the function).

    defmodule Demo do
      def transform(list) do
        import Enum, only: [map: 2]
        map(list, &(&1 + 1))
      end
    end
  

Here is another example importing both `map` and `filter` from `Enum`

    defmodule Demo do
      def transform(list) do
        import Enum, only: [map: 2, filter: 2]
        map(list, &(&1 + 1))
          |> filter(&(&1 === 3))
      end
    end
  

I prefer to be explicit with `only` most of the time but technically another import option exists called `except`. This will pull in all functions for a given module except what you specifically call out.

    defmodule Demo do
      def transform(list) do
        import Enum, except: [filter: 2]
        map(list, &(&1 + 1))
      end
    end
  

Buy Me a Coffee

Twitter / Github / Email