Elixir Language Behaviours Introduction

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Behaviours are a list of functions specifications that another module can implement. They are similar to interfaces in other languages.

Here’s an example behaviour:

defmodule Parser do
  @callback parse(String.t) :: any
  @callback extensions() :: [String.t]
end

And a module that implements it:

defmodule JSONParser do
  @behaviour Parser

  def parse(str), do: # ... parse JSON
  def extensions, do: ["json"]
end

The @behaviour module attribute above indicates that this module is expected to define every function defined in the Parser module. Missing functions will result in undefined behaviour function compilation errors.

Modules can have multiple @behaviour attributes.



Got any Elixir Language Question?