Please help me with example use case for WHEN in elixir

I want to know more about WHEN statement in elixir

1 Like

You are describing with, not when.

4 Likes

when is to introduce a guard in a pattern match.

It “refines” the values that have been bound through matching and can do shallow type or value checking:

n = 5
case get_user_input_as_number do
  x when is_integer(x) and x < n -> IO.puts("lesser")
  x when is_integer(x) and x > n -> IO.puts("bigger")
  ^n -> IO.puts("equal")
end
2 Likes

The section of the documentation where you can read more about when and guards, is the “Patterns and Guards” section. There are many examples there that are probably more clear than what we can come up with on the fly :slight_smile:.

5 Likes

Yeah, it was too early for me… Drink (coffee) before you write…

5 Likes