- Elixir Tutorial
- Elixir - Home
- Elixir - Overview
- Elixir - Environment
- Elixir - Basic Syntax
- Elixir - Data Types
- Elixir - Variables
- Elixir - Operators
- Elixir - Pattern Matching
- Elixir - Decision Making
- Elixir - Strings
- Elixir - Char Lists
- Elixir - Lists and Tuples
- Elixir - Keyword Lists
- Elixir - Maps
- Elixir - Modules
- Elixir - Aliases
- Elixir - Functions
- Elixir - Recursion
- Elixir - Loops
- Elixir - Enumerables
- Elixir - Streams
- Elixir - Structs
- Elixir - Protocols
- Elixir - File I/O
- Elixir - Processes
- Elixir - Sigils
- Elixir - Comprehensions
- Elixir - Typespecs
- Elixir - Behaviours
- Elixir - Errors Handling
- Elixir - Macros
- Elixir - Libraries
- Elixir Useful Resources
- Elixir - Quick Guide
- Elixir - Useful Resources
- Elixir - Discussion
Elixir - Case Statement
Case statement can be considered as a replacement for the switch statement in imperative languages. Case takes a variable/literal and applies pattern matching to it with different cases. If any case matches, Elixir executes the code associated with that case and exits the case statement. If no match is found, it exits the statement with an CaseClauseError that displays no matching clauses were found. You should always have a case with _ which matches all values. This helps in prevention of the above mentioned error. Also this is comparable to the default case in switch-case statements.
Syntax
The syntax of an if statement is as follows −
case value do matcher_1 -> #code to execute if value matches matcher_1 matcher_2 -> #code to execute if value matches matcher_2 matcher_3 -> #code to execute if value matches matcher_3 ... _ -> #code to execute if value does not match any of the above end
Example
case 3 do 1 -> IO.puts("Hi, I'm one") 2 -> IO.puts("Hi, I'm two") 3 -> IO.puts("Hi, I'm three") _ -> IO.puts("Oops, you dont match!") end
The above program generates the following result.
Hi, I'm three
Note that the case selection is done using pattern matching, so you can use the standard pattern matching techniques.