O'Reilly logo

Elixir Cookbook by Paulo A Pereira

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Enforcing behaviors

One of the reserved module attributes in Elixir is @behaviour. It is used to ensure that a given module implements the required callbacks and that the module implements a given interface and behaves in a defined way.

How to do it…

To demonstrate the use of the @behaviour module attribute, follow these steps:

  1. Create the Randomizer module inside the randomizer.ex file by adding the following code:
    defmodule Randomizer do
      use Behaviour
      defcallback randomize(low::Integer.t, high::Integer.t) :: Integer.t
    end
  2. Create a module to implement the Randomizer behavior inside the my_module.ex file by adding the following code:
    defmodule MyModule do
      @behaviour Randomizer
    end
  3. Open a new IEx session in the same directory where the modules defined ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required