scala essentials - pattern matching and case classes

Download Scala Essentials - Pattern Matching and Case Classes

Post on 01-Sep-2014

4.694 views

Category:

Technology

0 download

Embed Size (px)

DESCRIPTION

In-depth presentation about basics of pattern matching and case classes given by Karel Smutný at the April's Czech Scala Enthusiasts meetup held at Faculty of Information Technology in Prague.

TRANSCRIPT

  • CTU-FIT-SCA/scalaonfitIf youre gonna code,download the following Gisthttps://gist.github.com/ksmutny/5439360Czech Scala EnthusiastsApril 23 2013Scala Essentials: Pattern Matching and Case ClassesKarel SmutnAgile Developer & Coach
  • switch statementswitch (whatIsThis) {case 8:case 10:doSomething();break;case 12:doSomethingElse();break;default:doDefault();}match expressionwhatIsThis match {case 8 | 10 => somethingcase 12 => somethingElsecase _ => default}
  • Pattern Matchinga.k.a.Switch on steroids
  • Pattern Matchinga.k.a.Batmans toolbelt
  • https://gist.github.com/ksmutny/5439360sealed trait Character {def name: String}case class Civilian(name: String,wealth: Wealth) extends Charactercase class SuperHero(name: String,powers: List[Power],alterEgo: Option[Civilian]) extends Character
  • The ProblemWhat are the super powers of anunknown person if it is a superhero whos alter ego is TonyStark?
  • Javaif (unknownChar instanceof SuperHero) {final SuperHero hero = (SuperHero) unknownChar;if (hero.alterEgo.equals(tonyStark)) {return hero.powers;} else {return null;}} else {return null;}
  • ScalaunknownPerson match {case SuperHero(_, powers, Some(TonyStark)) =>Some(powers)case _ => None}
  • ScalaunknownPerson match {case SuperHero(_, powers, Some(TonyStark)) =>Some(powers)case _ => None}How cool is that?
  • JavaScriptunknownPerson.hasOwnPropery(powers) ?unknownPerson[powers] : null;
  • Kinds of patterns
  • Wildcard patternwhatIsThis match {case _ => anything!}
  • Constant patternwhatIsThis match {case 42 => a magic no.case Hello! => a greetingcase math.Pi => another magic no.case _ => something else}
  • Constant patternevaluating {BruceWayne match {case 42 => a magic no.case Hello! => a greetingcase math.Pi => another magic no.}} should produce[MatchError]
  • Variable patternwhatIsThis match {case something => not very useful?}
  • Variable patternwhatIsThis match {case whatIsThis => not very useful?}
  • Typed patternwhatIsThis match {case n: Int => aah, a numbercase c: Character => its + c.name}
  • Constructor patternunknownPerson match {case SuperHero(_, powers, Some(TonyStark)) =>Some(powers)case _ => None}
  • Constant v Variable patternval TonyStark = Civilian(Tony Stark, Fortune)val BruceWayne = Civilian(Bruce Wayne, Fortune)val clarkKent = Civilian(Clark Kent, Cash(1000))TonyStark match {case BruceWayne => Batman!case clarkKent => isnt this Superman?case _ => is he?}
  • Constant v Variable patternval TonyStark = Civilian(Tony Stark, Fortune)val BruceWayne = Civilian(Bruce Wayne, Fortune)val clarkKent = Civilian(Clark Kent, Cash(1000))TonyStark match {case BruceWayne => Batman!case `clarkKent` => Superman!case _ => anybody}
  • Constant v Variable patternval TonyStark = Civilian(Tony Stark, Fortune)val BruceWayne = Civilian(Bruce Wayne, Fortune)val clarkKent = Civilian(Clark Kent, Cash(1000))TonyStark match {case BruceWayne => Batman!case `clarkKent` => Superman!case _ => anybody}
  • Constructor patternval powers = unknownPerson match {case SuperHero(_, powers, Some(TonyStark)) =>Some(powers)case _ => None}val firstPower = powers match {case Some(power :: rest) => powercase _ => Genius}
  • Constructor patternval powers = unknownPerson match {case SuperHero(_, powers, Some(TonyStark)) =>Some(powers)case _ => None}val firstPower = powers match {case Some(power :: rest) => powercase _ => Genius}
  • Constructor patternval powers = unknownPerson match {case SuperHero(_, powers, Some(TonyStark)) =>Some(powers)case _ => None}val firstPower = powers match {case Some(power :: rest) => powercase _ => Genius}
  • Tuple patternaPair match {case (42, math.Pi, _) => magic numbers + anythingcase (IronMan, Mandarin) => hate each othercase Tuple2(IronMan, Mandarin) => alikecase (v: Villain, MaryJane) =>are cheating on Peter}
  • Sequence patternpowers match {case List(SuperStrength, _, _*) =>at least two}
  • Pattern guardaGuy match {case Civilian(_, Cash(money))if cash >= 10000 => Rich guycase _ => anybody else}
  • Patterns everywhere
  • Variable definitionval (a, b) = someTupleval List(Flight, second, rest @ _*) = powersval Civilian(name, wealth: Cash) = clarkKentIs this pattern matching, too?val a = 3
  • Exceptionstry {doSomethingStupid()} catch {case e: IOException => case e: SQLException => }
  • Partial functionval numToStr: PartialFunction[Int, String] = {case 8 => eightcase 10 => ten}numToStr.isDefinedAt(12)evaluating {numToStr(12)} should produce[??????????????]
  • For comprehensionsval lines = List(1t2,3t3,12,2t1,3t3,15,3t1,12t2,15)val edges = for {line age}
  • CaseClasses
  • No need for val in parameterscase class Villain(val name: String,val archenemy: SuperHero) extends Character
  • No need for val in parameterscase class Villain(val name: String,val archenemy: SuperHero) extends Character
  • No need for new keywordnew Villain(Mandarin, tonyStark)object Villain {def apply(name: String, archenemy: SuperHero) =new Villain(name, archenemy)}
  • No need for new keywordnew Villain(Mandarin, tonyStark)object Villain {def apply(name: String, archenemy: SuperHero) =new Villain(name, archenemy)}
  • No need for new keywordnew Villain(Mandarin, tonyStark)object Villain {def apply(name: String, archenemy: SuperHero) =new Villain(name, archenemy)}
  • equals and hashCodeval mandarin =Villain(Mandarin, tonyStark)mandarin ==Villain(Mandarin, tonyStark)val villainRank =Map(mandarin -> 81)
  • Intuitive toStringTonyStark.toString == Civilian(Tony Stark,Fortune)
  • Handy copy methodval batman = SuperHero(Batman,List(Genius, Gadgets),Civilian(Bruce Wayne, Fortune))val sixPack = batman.copy(powers = Nil)
  • and pattern matchingHow the heck ispattern matching donefor case classes?
  • Sealed classessealed trait Wealthcase class Cash(n: Int) extends Wealthcase object Fortune extends Wealth
  • Anyquestions?
  • Next meetup May 28, 2013Java 8 How does it compare toScala? A closer look at -expressionsimplementation Influences on futureScala versions, benefitsfor Scala developersScala 2.10 String Interpolation Value Classes Implicit Classes Macros
  • Next coding dojoMay14, 2013

Recommended

View more >