Beauty of Pattern Matching

2,748 views

Published on

First presentation at the Czech Scala Enthusiasts meetup on September 20, 2011.

Published in: Technology
1 Comment
2 Likes
Statistics
Notes
No Downloads
Views
Total views
2,748
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
37
Comments
1
Likes
2
Embeds 0
No embeds

No notes for slide

Beauty of Pattern Matching

  1. 1. Beauty of patternmatching in ScalaKarel SmutnýCzech Scala Enthusiast1st meet-up, September 20, 2011
  2. 2. Agenda• Scala match expression v Java switch• What is pattern matching• Pattern types• Extractors• Other uses ▫ Variables declaration ▫ for expressions ▫ catch clauses ▫ Regular expressions ▫ XML• Pattern matching v Visitor Pattern
  3. 3. Scala match v Java switchmatch switchsomeFlag match { switch (someFlag) { case 1 | 2 => doSomething() case 1: case 3 => doSomethingElse() case 2: case _ => doSomethingDefault() doSomething();} break; case 3: doSomethingElse(); break; default: doSomethingDefault(); }
  4. 4. Scala match v Java switchmatch switch• Expression • Statement• Returns value of the first matched • Pesky break keyword alternative • Only some primitive types, String• Much, much, much more powerful and enum, only literals/constants
  5. 5. What is pattern matching?• Wiki: “…pattern matching is the act of checking some sequence of tokens for the presence of the constituents of some pattern.”
  6. 6. Wildcard pattern obj match { case _ => ... }• Matches anything• Used as a default; if not present, compiler emits a warning
  7. 7. Variable pattern obj match { case anotherName => ... }• Matches anything, creates new variable• Uses type inference
  8. 8. Type pattern obj match { case str: String => … } if ((obj instanceof String) && (obj != null)) { String str = (String) obj; … }
  9. 9. Constant pattern obj match { case 4 => … case DasObject => … case `existingVariable` => … }• Matches exact value, in terms of ==
  10. 10. Tuple pattern obj match { case (4, _, “some text”) => … case (a: Int, b: Double) => … }• Matches if obj is proper TupleX and all its fields match
  11. 11. Constructor pattern case class Person(name: String, age: Int) obj match { case Person(_, 25) => … case Person(“Jarda”, age) => … case Person(_, age) if age >= 18 => … }• Matches if value.isInstance[Person] and appropriate attributes match (imagine this in Java)• Works only for case classes (does it?)
  12. 12. Sequence pattern obj match { case List(_, 2, x) => … case List(1, 2, 3, _*) => … case head :: tail => … }• Matches variable number of arguments (vararg)• _* matches any number of other arguments, including none
  13. 13. Extractor• What about non-case classes? class Person(val name: String, val age: Int) object Person { def unapply(p: Person): Option[(String, Int)] = Some(p.name, p.age) } obj match { case Person(_, 25) => … case Person(“Jarda”, age) => … case Person(_, age) if age >= 18 => … }
  14. 14. Other types of extractors• Sequence pattern matching def unapplySeq(a: SomeClass): Option[Seq[?]]• One argument only (there is no Tuple1) def unapply(a: SomeClass): Option[Int]• Note the parentheses (otherwise it would be constant pattern) def unapply(a: SomeClass): Boolean value match { case SomeClass() => … }
  15. 15. Other uses: Variable declaration• You may use pattern matching to declare variables: val (a, b, c) = (5, “text”, someFunction) val (a, _) = (5, “to be forgotten forever”) val Person(name, age) = somePerson• Geez! Look at this. It’s a pattern matching! val a = 5
  16. 16. Other uses: for expression• You may use pattern matching in for expressions: val personList: List[Person] = ... for (Person(name, age) <- personList) ...• Don’t forget unapply() on iterated elements
  17. 17. Other uses: catch clause• This is pattern matching, too: try { doSomethingStupid() } catch { case e: IllegalArgumentException => ... case SomeCustomException(someDetail) => ... case _ => ... }
  18. 18. Other uses: Regular expressions• Guess where is the unapply() method: val person = “““^(w)+,(d)+$”””.r someInput match { case person(name, age) => ... }• Here it is: class Regex { def unapplySeq(target: Any): Option[List[String]] }
  19. 19. Other uses: XML• Just a teaser (XML pattern matching is out of scope of this talk): catalog match { case <catalog>{therms @ _*}</catalog> => for (therm @ <cctherm>{_*}</cctherm> <- therms) ... }
  20. 20. Topic for discussion: Visitor pattern

×