links: Elixir MOC


cond is used when you need to match against different values. However, in many cases, we want to check different conditions and find one that does not evaluate to nil or false

cond do
  2 + 2 == 5 ->
    "This will not be true"
  2 * 2 == 3 ->
    "Nor this"
  1 + 1 == 2 ->
    "But this will"
end
 
# => But this will

This is equivalent to else if in many imperative programming languages.

if all the conditions return nil or false an error (CondClassError) is raised during runtime, For this reason, it maybe necessary to add a final condition true which will always match.

cond considers any value besides nil and false to be true


tags: elixir conditionals

sources: