O'Reilly logo

Programming Elixir by Dave Thomas

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

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. Either 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 functions, 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>

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