In Elixir, if and its evil twin, unless, take two parameters: a condition and a keyword list, which can contain the keys do: and else:. If the condition is truthy, the if expression evaluates the code associated with the do: key; otherwise it evaluates the else: code. The else: branch may be absent.
| iex> if 1 == 1, do: "true part", else: "false part" |
| "true part" |
| iex> if 1 == 2, do: "true part", else: "false part" |
| "false part" |
Just as it does with function definitions, Elixir provides some syntactic sugar. You can write the first of the previous examples as follows:
| iex> if 1 == 1 do |
| ...> "true part" |
| ...> else |
| ...> "false part" |
| ...> end |
| true part |
unless is similar:
| iex> unless 1 == 1, do: "error", else: "OK" |
| "OK" |
| iex> unless 1 == 2, do: "OK", else: "error" |
| "OK" |
| iex> unless 1 == 2 do |
| ...> "OK" |
| ...> else |
| ...> "error" |
| ...> end |
| "OK" |
The value of if and unless is the value of the expression that was evaluated.