SlideShare a Scribd company logo
Pattern matching
myObject   match {
  case 1   => println("First was hit")
  case 2   => println("Second was Hit")
  case _   => println("Unknown")
}
myObject match {
   case i: Int => println("Found an int")
   case s: String => println("Found a String")
   case _ => println("Unknown")
 }
myObject match {
   case i: Int => println("Found an int")
   case s: String => println("Found an String")
   case other => println("Unknown " + other)
 }
myObject match {
   case i: Int if i == 1 => println("Found an int")
   case s: String => println("Found a String")
   case other => println("Unknown " + other)
 }
val res = myObject match {
    case i: Int if i == 1 => "Found an int"
    case s: String => "Found a String"
    case other => "Unknown " + other
}
val res = myObject match {
    case (first, second) => second
    case (first, second, third) => third
}
val mathedElement = list match {
  case List(firstElement, lastElement) => firstElement
  case List(firstElement, _ *) => firstElement
  case _ => "failed"
}
def length(list: List[_]): Int =
  list match {
    case Nil => 0
    case head :: tail => 1 + length(tail)
  }
public static Integer getSecondOr0(List<Integer> list) {
    if (list != null && list.size() >= 2) {
        return list.get(1);
    } else {
        return 0;
    }
}




def second_or_0(list:List[Int]) = list match {
  case List(_, x, _*) => x
  case _ => 0
}
Case classes
Class types that can be used in pattern matching
Generated into your class:
  equals
  hashCode
  toString
  getters (and optionally setters)
  ++
abstract class Person(name: String)
case class Man(name: String) extends Person(name)
case class Woman(name: String, children: List[Person])
  extends Person(name)
p match {
  case Man(name) => println("Man with name " + name)
  case Woman(name, children) => println("Woman with name "
                              + name + " and with " +
                                children.size + " children")
}
val regex = """(d+)(w+)""".r

val myString = ...

val res: String = myString match {
  case regex(digits, word) => digits
  case _ => "None"
}
val regex = """(d+)(w+)""".r

val myString = ...

val res: Option[String] = myString match {
  case regex(digit, word) => Some(digit)
  case _ => None
}
The Option type, never again
       NullPointerException
Option has two possible values
  Some(value)
  None



  val someOption: Option[String] = Some("value")
  val noOption:   Option[String] = None
def getValue(s: Any): Option[String]




getValue(object) match {
  case Some(value) => println(value)
  case None => println("Nothing")
}



val result = getValue(object).getOrElse("Nothing")
Tasks (30 min)
Open the 'pattern-matching' project
Tests in package scalaexamples.patternmatching
Add @Test to one and one method
Follow instructions in the code
Make the tests pass

More Related Content

What's hot

4.3 derivatives of inv erse trig. functions
4.3 derivatives of inv erse trig. functions4.3 derivatives of inv erse trig. functions
4.3 derivatives of inv erse trig. functions
dicosmo178
 
4.4 l'hopital's rule
4.4 l'hopital's rule4.4 l'hopital's rule
4.4 l'hopital's rule
dicosmo178
 
4.3 derivative of exponential functions
4.3 derivative of exponential functions4.3 derivative of exponential functions
4.3 derivative of exponential functions
dicosmo178
 

What's hot (16)

The Ring programming language version 1.9 book - Part 38 of 210
The Ring programming language version 1.9 book - Part 38 of 210The Ring programming language version 1.9 book - Part 38 of 210
The Ring programming language version 1.9 book - Part 38 of 210
 
Apuntes clojure
Apuntes clojureApuntes clojure
Apuntes clojure
 
Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!
 
Master's Thesis
Master's ThesisMaster's Thesis
Master's Thesis
 
Day 3 of Free Intuitive Calculus Course: Limits by Factoring
Day 3 of Free Intuitive Calculus Course: Limits by FactoringDay 3 of Free Intuitive Calculus Course: Limits by Factoring
Day 3 of Free Intuitive Calculus Course: Limits by Factoring
 
Day 2: Basic Properties of Limits
Day 2: Basic Properties of LimitsDay 2: Basic Properties of Limits
Day 2: Basic Properties of Limits
 
The Ring programming language version 1.5.2 book - Part 35 of 181
The Ring programming language version 1.5.2 book - Part 35 of 181The Ring programming language version 1.5.2 book - Part 35 of 181
The Ring programming language version 1.5.2 book - Part 35 of 181
 
Dependent Types with Idris
Dependent Types with IdrisDependent Types with Idris
Dependent Types with Idris
 
The Ring programming language version 1.2 book - Part 20 of 84
The Ring programming language version 1.2 book - Part 20 of 84The Ring programming language version 1.2 book - Part 20 of 84
The Ring programming language version 1.2 book - Part 20 of 84
 
Limits by Factoring
Limits by FactoringLimits by Factoring
Limits by Factoring
 
Hash table and heaps
Hash table and heapsHash table and heaps
Hash table and heaps
 
The Ring programming language version 1.5.2 book - Part 30 of 181
The Ring programming language version 1.5.2 book - Part 30 of 181The Ring programming language version 1.5.2 book - Part 30 of 181
The Ring programming language version 1.5.2 book - Part 30 of 181
 
The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.10 book - Part 47 of 212The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.10 book - Part 47 of 212
 
4.3 derivatives of inv erse trig. functions
4.3 derivatives of inv erse trig. functions4.3 derivatives of inv erse trig. functions
4.3 derivatives of inv erse trig. functions
 
4.4 l'hopital's rule
4.4 l'hopital's rule4.4 l'hopital's rule
4.4 l'hopital's rule
 
4.3 derivative of exponential functions
4.3 derivative of exponential functions4.3 derivative of exponential functions
4.3 derivative of exponential functions
 

Viewers also liked

Viewers also liked (9)

2.4 xml support
2.4 xml support2.4 xml support
2.4 xml support
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_one
 
1.4 first class-functions
1.4 first class-functions1.4 first class-functions
1.4 first class-functions
 
1.3 tools and-repl
1.3 tools and-repl1.3 tools and-repl
1.3 tools and-repl
 
1.7 functional programming
1.7 functional programming1.7 functional programming
1.7 functional programming
 
1.6 oo traits
1.6 oo traits1.6 oo traits
1.6 oo traits
 
2.3 implicits
2.3 implicits2.3 implicits
2.3 implicits
 
2.2 higher order-functions
2.2 higher order-functions2.2 higher order-functions
2.2 higher order-functions
 
2.5 the quiz-game
2.5 the quiz-game2.5 the quiz-game
2.5 the quiz-game
 

Similar to 1.5 pattern matching

2.1 Recap From Day One
2.1 Recap From Day One2.1 Recap From Day One
2.1 Recap From Day One
retronym
 

Similar to 1.5 pattern matching (20)

Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
Scala taxonomy
Scala taxonomyScala taxonomy
Scala taxonomy
 
Benefits of Kotlin
Benefits of KotlinBenefits of Kotlin
Benefits of Kotlin
 
2.1 Recap From Day One
2.1 Recap From Day One2.1 Recap From Day One
2.1 Recap From Day One
 
Kotlin, Spek and tests
Kotlin, Spek and testsKotlin, Spek and tests
Kotlin, Spek and tests
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版
 
Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.Python: легко и просто. Красиво решаем повседневные задачи.
Python: легко и просто. Красиво решаем повседневные задачи.
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
 
Functional DDD
Functional DDDFunctional DDD
Functional DDD
 
Scala in a Java 8 World
Scala in a Java 8 WorldScala in a Java 8 World
Scala in a Java 8 World
 
Scala for Jedi
Scala for JediScala for Jedi
Scala for Jedi
 

Recently uploaded

anas about venice for grade 6f about venice
anas about venice for grade 6f about veniceanas about venice for grade 6f about venice
anas about venice for grade 6f about venice
anasabutalha2013
 
Sustainability: Balancing the Environment, Equity & Economy
Sustainability: Balancing the Environment, Equity & EconomySustainability: Balancing the Environment, Equity & Economy
Sustainability: Balancing the Environment, Equity & Economy
Operational Excellence Consulting
 
Memorandum Of Association Constitution of Company.ppt
Memorandum Of Association Constitution of Company.pptMemorandum Of Association Constitution of Company.ppt
Memorandum Of Association Constitution of Company.ppt
seri bangash
 
FINAL PRESENTATION.pptx12143241324134134
FINAL PRESENTATION.pptx12143241324134134FINAL PRESENTATION.pptx12143241324134134
FINAL PRESENTATION.pptx12143241324134134
LR1709MUSIC
 

Recently uploaded (20)

Skye Residences | Extended Stay Residences Near Toronto Airport
Skye Residences | Extended Stay Residences Near Toronto AirportSkye Residences | Extended Stay Residences Near Toronto Airport
Skye Residences | Extended Stay Residences Near Toronto Airport
 
anas about venice for grade 6f about venice
anas about venice for grade 6f about veniceanas about venice for grade 6f about venice
anas about venice for grade 6f about venice
 
Understanding UAE Labour Law: Key Points for Employers and Employees
Understanding UAE Labour Law: Key Points for Employers and EmployeesUnderstanding UAE Labour Law: Key Points for Employers and Employees
Understanding UAE Labour Law: Key Points for Employers and Employees
 
Maximizing Efficiency Migrating AccountEdge Data to QuickBooks.pdf
Maximizing Efficiency Migrating AccountEdge Data to QuickBooks.pdfMaximizing Efficiency Migrating AccountEdge Data to QuickBooks.pdf
Maximizing Efficiency Migrating AccountEdge Data to QuickBooks.pdf
 
G-Mica Wood Chip Particle board Table Design
G-Mica Wood Chip Particle board Table DesignG-Mica Wood Chip Particle board Table Design
G-Mica Wood Chip Particle board Table Design
 
Transforming Max Life Insurance with PMaps Job-Fit Assessments- Case Study
Transforming Max Life Insurance with PMaps Job-Fit Assessments- Case StudyTransforming Max Life Insurance with PMaps Job-Fit Assessments- Case Study
Transforming Max Life Insurance with PMaps Job-Fit Assessments- Case Study
 
12 Conversion Rate Optimization Strategies for Ecommerce Websites.pdf
12 Conversion Rate Optimization Strategies for Ecommerce Websites.pdf12 Conversion Rate Optimization Strategies for Ecommerce Websites.pdf
12 Conversion Rate Optimization Strategies for Ecommerce Websites.pdf
 
Strategy Analysis and Selecting ( Space Matrix)
Strategy Analysis and Selecting ( Space Matrix)Strategy Analysis and Selecting ( Space Matrix)
Strategy Analysis and Selecting ( Space Matrix)
 
Sustainability: Balancing the Environment, Equity & Economy
Sustainability: Balancing the Environment, Equity & EconomySustainability: Balancing the Environment, Equity & Economy
Sustainability: Balancing the Environment, Equity & Economy
 
What are the main advantages of using HR recruiter services.pdf
What are the main advantages of using HR recruiter services.pdfWhat are the main advantages of using HR recruiter services.pdf
What are the main advantages of using HR recruiter services.pdf
 
Using Generative AI for Content Marketing
Using Generative AI for Content MarketingUsing Generative AI for Content Marketing
Using Generative AI for Content Marketing
 
Improving profitability for small business
Improving profitability for small businessImproving profitability for small business
Improving profitability for small business
 
Memorandum Of Association Constitution of Company.ppt
Memorandum Of Association Constitution of Company.pptMemorandum Of Association Constitution of Company.ppt
Memorandum Of Association Constitution of Company.ppt
 
IPTV Subscription UK: Your Guide to Choosing the Best Service
IPTV Subscription UK: Your Guide to Choosing the Best ServiceIPTV Subscription UK: Your Guide to Choosing the Best Service
IPTV Subscription UK: Your Guide to Choosing the Best Service
 
Equinox Gold Corporate Deck May 24th 2024
Equinox Gold Corporate Deck May 24th 2024Equinox Gold Corporate Deck May 24th 2024
Equinox Gold Corporate Deck May 24th 2024
 
Putting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptxPutting the SPARK into Virtual Training.pptx
Putting the SPARK into Virtual Training.pptx
 
Accpac to QuickBooks Conversion Navigating the Transition with Online Account...
Accpac to QuickBooks Conversion Navigating the Transition with Online Account...Accpac to QuickBooks Conversion Navigating the Transition with Online Account...
Accpac to QuickBooks Conversion Navigating the Transition with Online Account...
 
BeMetals Presentation_May_22_2024 .pdf
BeMetals Presentation_May_22_2024   .pdfBeMetals Presentation_May_22_2024   .pdf
BeMetals Presentation_May_22_2024 .pdf
 
Lookback Analysis
Lookback AnalysisLookback Analysis
Lookback Analysis
 
FINAL PRESENTATION.pptx12143241324134134
FINAL PRESENTATION.pptx12143241324134134FINAL PRESENTATION.pptx12143241324134134
FINAL PRESENTATION.pptx12143241324134134
 

1.5 pattern matching

  • 2. myObject match { case 1 => println("First was hit") case 2 => println("Second was Hit") case _ => println("Unknown") }
  • 3. myObject match { case i: Int => println("Found an int") case s: String => println("Found a String") case _ => println("Unknown") }
  • 4. myObject match { case i: Int => println("Found an int") case s: String => println("Found an String") case other => println("Unknown " + other) }
  • 5. myObject match { case i: Int if i == 1 => println("Found an int") case s: String => println("Found a String") case other => println("Unknown " + other) }
  • 6. val res = myObject match { case i: Int if i == 1 => "Found an int" case s: String => "Found a String" case other => "Unknown " + other }
  • 7. val res = myObject match { case (first, second) => second case (first, second, third) => third }
  • 8. val mathedElement = list match { case List(firstElement, lastElement) => firstElement case List(firstElement, _ *) => firstElement case _ => "failed" }
  • 9. def length(list: List[_]): Int = list match { case Nil => 0 case head :: tail => 1 + length(tail) }
  • 10. public static Integer getSecondOr0(List<Integer> list) { if (list != null && list.size() >= 2) { return list.get(1); } else { return 0; } } def second_or_0(list:List[Int]) = list match { case List(_, x, _*) => x case _ => 0 }
  • 11. Case classes Class types that can be used in pattern matching Generated into your class: equals hashCode toString getters (and optionally setters) ++
  • 12. abstract class Person(name: String) case class Man(name: String) extends Person(name) case class Woman(name: String, children: List[Person]) extends Person(name)
  • 13. p match { case Man(name) => println("Man with name " + name) case Woman(name, children) => println("Woman with name " + name + " and with " + children.size + " children") }
  • 14. val regex = """(d+)(w+)""".r val myString = ... val res: String = myString match { case regex(digits, word) => digits case _ => "None" }
  • 15. val regex = """(d+)(w+)""".r val myString = ... val res: Option[String] = myString match { case regex(digit, word) => Some(digit) case _ => None }
  • 16. The Option type, never again NullPointerException Option has two possible values Some(value) None val someOption: Option[String] = Some("value") val noOption: Option[String] = None
  • 17. def getValue(s: Any): Option[String] getValue(object) match { case Some(value) => println(value) case None => println("Nothing") } val result = getValue(object).getOrElse("Nothing")
  • 18. Tasks (30 min) Open the 'pattern-matching' project Tests in package scalaexamples.patternmatching Add @Test to one and one method Follow instructions in the code Make the tests pass