if and unless

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: ...

Get Programming Elixir ≥ 1.6 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.