O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

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

Matching All the Things

So far we’ve just scratched the surface of pattern matching. Scala allows you to match based on values and types; you can even use guarded cases using if, as you’ll see next.

 def process(message : Any) = {
  message match {
  case "hello" => println("received hello")
  case x : String => println("received a string " + x)
  case (a, b) => println("received tuple (" + a + ", " + b + ")")
  case 22 => println("received 22")
  case x : Int if x < 0 => println("received a negative number " + x)
  case y : Int => println("received number " + y)
  }
 }
 process(1, 2) // received typle (1, 2)
 process("hello") // received hello
 process("test") // received a string test
 process(22) // received 22
 process(12) // received number ...

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