Pattern Matching in Scala | ASSIST Software Romania
get in touch
>

LIKE

SHARE

Facebook Share Tweet LinkedIn Share

FOLLOW

LinkedIn Follow Xing Follow
Ciprian Sofronia

Android Developer at ASSIST

Pattern matching is one of many things that Scala can do.

Think „switch” on steroids. What happens if you have to match one or more patterns in a match expression, and the pattern may be a constant, variable, constructor, sequence, tuple, or type pattern. In Scala this is kid's play.

The following example explains how this could be made in Scala.

def echoWhateverYouGaveMe(x: Any): String = x match {

   // constant patterns
   case 0 => "zero"
   case true => "true"
   case "hello" => "you said 'hello'"
   case Nil => "an empty List"

   // sequence patterns
   case List(0, _, _) => "a three-element list with 0 as the first element"
   case List(1, _*) => "a list beginning with 1, having any number of elements"
   case Vector(1, _*) => "a vector starting with 1, having any number of elements"

   // tuples
   case (a, b) => s"got $a and $b"
   case (a, b, c) => s"got $a, $b, and $c"

   // constructor patterns
   case Person(first, "Alexander") => s"found an Alexander, first name = $first"
   case Dog("Suka") => "found a dog named Suka"

   // typed patterns
   case s: String => s"you gave me this string: $s"
   case i: Int => s"thanks for the int: $i"
   case f: Float => s"thanks for the float: $f"
   case a: Array[Int] => s"an array of int: ${a.mkString(",")}"
   case as: Array[String] => s"an array of strings: ${as.mkString(",")}"
   case d: Dog => s"dog: ${d.name}"
   case list: List[_] => s"thanks for the List: $list"
   case m: Map[_, _] => m.toString

   // the default wildcard pattern
   case _ => "Unknown"

   // adding if expressions
   case a if 0 to 9 contains a => println("0-9 range: " + a)
   case b if 10 to 19 contains b => println("10-19 range: " + b)
   case x if x == 1 => println("one, a lonely number") 
   case x if (x == 2 || x == 3) => println(x)
   case _ => println("some other value")

   // matching multiple conditions with one case statement
   case 1 | 3 | 5 | 7 | 9 => println("odd")
   case 2 | 4 | 6 | 8 | 10 => println("even")
}

Möchten Sie mit uns in Kontakt treten?

Wenn Sie an unseren Softwareentwicklungsdienstleistungen interessiert sind, sich unserem Team anschließen möchten oder einfach mehr über uns erfahren möchten, würden wir uns freuen, von Ihnen zu hören! Schreiben Sie uns ein paar Zeilen und ein Mitglied des ASSIST-Teams wird sich so schnell wie möglich bei Ihnen melden. Wir sind sicher, dass wir Ihnen helfen können.

SETZEN SIE SICH MIT UNS IN VEBINDUNG!