21 Match as a Switch

Pattern matching will be familiar to anyone coming from a Haskell background, however it might look a bit weird at first for anyone coming from imperative languages.

Pattern matching in it’s most basic form, can look like an extended switch, with some differences:

  • The match keyword comes after the variable (selection match compared to switch(selection)
  • There is no need for break;
  • There is no fall through
  • default case is case _ (or case x where x can be any lower case identifier, more about it in the next slides)

Pattern matching can be very powerful beyond a switch replacement, and will be explained in later slides


See Also opens in new page

0
val selection = "One"  
1
selection match {  
2
  case "One" => println("You selected option one!")  
3
  case "Two" => println("You selected option two!")  
4
  case _ => println("You selected something else: ")  
5
}  
6
 
 
Code editor is using Scalakata.com written by Guillaume Massé