Elixir is a dynamically written language, so all the types are checked at runtime. Typespec notation is used in Elixir for two main purposes:
:ok
and :error
, can be used with dynamic dispatching to make the program immune to errors.
Here is an example of a program that turns sentences upper-case or lower-case:
# Defining behaviourdefmodule CaseSensitive do# Declaring callback to be used@callback convert_case(sentence :: String) :: {:ok, String} | {:error, String}# Dynamic Dispatchingdef dispatcher!(implementation, contents) docase implementation.convert_case(contents) do{:ok, data} -> IO.puts(data){:error, error} -> raise ArgumentError, "#{error}"endendend# Function to make sentence uppercasedefmodule UpperCaseIt do@behaviour CaseSensitive@impl CaseSensitivedef convert_case(sentence) dotry do{:ok, String.upcase(sentence)}rescueFunctionClauseError -> {:error, "Custom error message"}endendend# Function to make sentence lower casedefmodule LowerCaseIt do@behaviour CaseSensitive@impl CaseSensitivedef convert_case(sentence) dotry do{:ok, String.downcase(sentence)}rescueFunctionClauseError -> {:error, "Custom error message"}endendendCaseSensitive.dispatcher!(UpperCaseIt, "turn this in uppercase")CaseSensitive.dispatcher!(LowerCaseIt, "TURN THIS IN LOWER CASE")CaseSensitive.dispatcher!(UpperCaseIt, 5555)
CaseSensitive
.CaseSensitive
behavior will have to implement the @callback
attributes in that behavior. In this case, there is only one attribute declared, convert_case
.convert_case
takes string as input and returns a tuple: {:ok, String}
returns if the execution is successful and {:error, String}
if the execution fails.dispatcher!
. This function acts as a mediator – it goes to a particular function and returns the value received from it.UpperCaseIt
and LowerCaseIt
functions are declared that contain the try/rescue
block. The function tries to execute the task in the try block, .upcase()
or .downcase()
, and then return the tuple to dispatcher!
accordingly.As a whole, this program has a couple of functions that execute their task and return the required result with an :ok
atom upon success; upon failure, it returns an :error
atom and a customized error message.
Free Resources