Private functions in Elixir

Published October 02, 2018 by Toran Billups

In part 9 of my Elixir journey I'll be showing how to create functions that are only visible within a module.

Privacy

So far all the named functions I've used in this blog series have been public. Elixir does allow you to create a private function using the `defp` keyword.

    defmodule Math do
      defp add(a) do
        fn (b) -> a + b end
      end
      def add_one(n) do
        add_fun = add(1)
        add_fun.(n)
      end
    end
  

In this example, the `add_one` function is our public api and internally this function will use `add` to create a function that is later used to do the addition work.

    Math.add_one(4)
  

The interesting bit here is that if we try to use the private function `add` we get an error because that function was declared using the `defp` keyword (macro).

`UndefinedFunctionError function Math.add/1 is undefined or private`


Buy Me a Coffee

Twitter / Github / Email