• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Scala Essentials - Pattern Matching and Case Classes
 

Scala Essentials - Pattern Matching and Case Classes

on

  • 3,941 views

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.

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.

Statistics

Views

Total Views
3,941
Views on SlideShare
3,939
Embed Views
2

Actions

Likes
3
Downloads
30
Comments
0

1 Embed 2

http://news.google.com 2

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Scala Essentials - Pattern Matching and Case Classes Scala Essentials - Pattern Matching and Case Classes Presentation Transcript

    • CTU-FIT-SCA/scalaonfitIf you’re gonna code,download the following Gisthttps://gist.github.com/ksmutny/5439360Czech Scala Enthusiasts–April 23 2013Scala Essentials: Pattern Matching and Case ClassesKarel Smutný–Agile 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.Batman’s 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 who’s 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 greeting”case math.Pi => “another magic no.”case _ => “something else”}
    • Constant patternevaluating {BruceWayne match {case 42 => “a magic no.”case “Hello!” => “a greeting”case 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 number”case c: Character => “it’s ” + 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 => “isn’t 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 + anything”case (IronMan, Mandarin) => “hate each other”case Tuple2(IronMan, Mandarin) => “alike”case (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 guy”case _ => “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 => “eight”case 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 <- linesArray(srcNode, edges @ _*) = line split “t”edge <- edgesArray(destNode, length) = edge split “,”} yield Edge(srcNode.toInt, destNode.toInt, length.toInt)
    • For comprehensions. Beware!val egos = for {hero : SuperHero <- characters // does not work} yield hero.alterEgoval egos = for {hero @ (h : SuperHero) <- characters} yield hero.alterEgo
    • ExtractorsExtractors
    • trait Person {def name: Stringdef age: Int}object Person {def unapply(person: Person): Option[(String, Int)] =Some((person.name, age))}somePerson match {case Person(“Moses”, _) => 969case Person(name, age) => age}
    • trait Person {def name: Stringdef age: Int}object Person {def unapply(person: Person): Option[(String, Int)] =Some((person.name, age))}somePerson match {case Person(“Moses”, _) => 969case Person(name, age) => 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 dojo–May14, 2013