SlideShare a Scribd company logo
1 of 23
Pattern Matching
                                   - at a glance




Neelkanth Sachdeva

Software Consultant

Knoldus Software LLP , New Delhi

neelkanthsachdeva.wordpress.com

neelkanth@knoldus.com

@NeelSachdeva
What is Case class ?

Before diving in to pattern matching lets talk
about case classes briefly.


Classes with case modifier are called case
Classes. Using the modifier makes the Scala
compiler add some syntactic conveniences to
your class.
What case modifier does ?

1. Adds a factory method with the name of the
  class. It eliminates the need of new during
  instantiation.
2. The second syntactic convenience is that all
  arguments in the parameter list of a case class
  implicitly get a val prefix, so they are
  maintained as fields
3. The compiler adds “natural” implementations
   of following methods to your class.
- toString,
- hashCode
- equals




4. The compiler adds a copy method to your class
  for making modified copies.
Pattern matching
The right-hand side of simplifyTop consists of a
match expression. match corresponds to switch
in Java.

Scala :
selector match { alternatives }

Java :
switch (selector) { alternatives }
- A pattern match includes a sequence of alternatives,
  each starting with the keyword case.

- Each alternative includes a pattern and one or more
  expressions, which will be evaluated if the pattern
  matches.

- An arrow symbol => separates the pattern from the
  expressions.

- A match expression is evaluated by trying each of the
  patterns in the order they are written. The first pattern
  that matches is selected, and the part following the
  arrow is selected and executed.
Kinds of patterns
1. Wildcard patterns
The wildcard pattern ( _ ) matches any object
whatsoever.It is used as a default.
2. Constant patterns

A constant pattern matches only itself. Any literal
may be used as a constant.
For example, 5, true, and "hello" are all constant
patterns. Also, any val or singleton object can be
used as a constant.
3. Variable patterns
A variable pattern matches any object, just like a
Wildcard. The default case uses a variable
pattern so that it has a name for the value, no
matter what it is.
4. Constructor patterns
A constructor pattern looks like :
BinOp("+", Number(0) , Number(0))
It consists of a name BinOp and then a number
of patterns within parenthese. Assuming the name designates a
case class, such a pattern means to first check that the object
is a member of the named case class, and then to check that the
constructor parameters of the object match the extra
patterns supplied.
5.Sequence patterns

You can match against sequence types like List
or Array just like you match against case
classes.
Use the same syntax, but now you can specify
any number of elements within the pattern.
6. Tuple patterns

You can match against tuples as well. A pattern
like (a, b, c) matches an arbitrary 3-tuple.
7.Typed patterns

You can use a typed pattern as a convenient
replacement for type tests and type casts.
Patterns in variable definitions

Any time you define a val or a var, you can use a
pattern instead of a simple identifier.
Patterns in for expressions
References

Programming in Scala by Martin Odersky
Pattern Matching - at a glance

More Related Content

What's hot

Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
Sandesh Sharma
 

What's hot (18)

Xml processing in scala
Xml processing in scalaXml processing in scala
Xml processing in scala
 
Programming in Scala - Lecture Three
Programming in Scala - Lecture ThreeProgramming in Scala - Lecture Three
Programming in Scala - Lecture Three
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
 
Functors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In ScalaFunctors, Applicatives and Monads In Scala
Functors, Applicatives and Monads In Scala
 
Programming in Scala - Lecture Four
Programming in Scala - Lecture FourProgramming in Scala - Lecture Four
Programming in Scala - Lecture Four
 
Linq Introduction
Linq IntroductionLinq Introduction
Linq Introduction
 
Programming in Scala - Lecture One
Programming in Scala - Lecture OneProgramming in Scala - Lecture One
Programming in Scala - Lecture One
 
Books
BooksBooks
Books
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
Python Programming - V. Sequences (List and Tuples) and Dictionaries
Python Programming - V. Sequences (List and Tuples) and DictionariesPython Programming - V. Sequences (List and Tuples) and Dictionaries
Python Programming - V. Sequences (List and Tuples) and Dictionaries
 
Scala test
Scala testScala test
Scala test
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
Scala oo (1)
Scala oo (1)Scala oo (1)
Scala oo (1)
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 
Of Lambdas and LINQ
Of Lambdas and LINQOf Lambdas and LINQ
Of Lambdas and LINQ
 

Similar to Pattern Matching - at a glance

Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
phanleson
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
Raghu nath
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9
Vince Vo
 

Similar to Pattern Matching - at a glance (20)

OCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIsOCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIs
 
Java
JavaJava
Java
 
Java Tutorial Lab 3
Java Tutorial Lab 3Java Tutorial Lab 3
Java Tutorial Lab 3
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 
2.regular expressions
2.regular expressions2.regular expressions
2.regular expressions
 
String handling
String handlingString handling
String handling
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
Java
JavaJava
Java
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Python - Regular Expressions
Python - Regular ExpressionsPython - Regular Expressions
Python - Regular Expressions
 
C# String
C# StringC# String
C# String
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
stringstringbuilderstringbuffer-190830060142.pptx
stringstringbuilderstringbuffer-190830060142.pptxstringstringbuilderstringbuffer-190830060142.pptx
stringstringbuilderstringbuffer-190830060142.pptx
 
Ruby Interview Questions
Ruby Interview QuestionsRuby Interview Questions
Ruby Interview Questions
 
easyPy-Basic.pdf
easyPy-Basic.pdfeasyPy-Basic.pdf
easyPy-Basic.pdf
 
Java căn bản - Chapter9
Java căn bản - Chapter9Java căn bản - Chapter9
Java căn bản - Chapter9
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Intro To Scala
Intro To ScalaIntro To Scala
Intro To Scala
 

More from Knoldus Inc.

More from Knoldus Inc. (20)

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 

Pattern Matching - at a glance

  • 1. Pattern Matching - at a glance Neelkanth Sachdeva Software Consultant Knoldus Software LLP , New Delhi neelkanthsachdeva.wordpress.com neelkanth@knoldus.com @NeelSachdeva
  • 2. What is Case class ? Before diving in to pattern matching lets talk about case classes briefly. Classes with case modifier are called case Classes. Using the modifier makes the Scala compiler add some syntactic conveniences to your class.
  • 3. What case modifier does ? 1. Adds a factory method with the name of the class. It eliminates the need of new during instantiation.
  • 4. 2. The second syntactic convenience is that all arguments in the parameter list of a case class implicitly get a val prefix, so they are maintained as fields
  • 5. 3. The compiler adds “natural” implementations of following methods to your class. - toString, - hashCode - equals 4. The compiler adds a copy method to your class for making modified copies.
  • 7. The right-hand side of simplifyTop consists of a match expression. match corresponds to switch in Java. Scala : selector match { alternatives } Java : switch (selector) { alternatives }
  • 8. - A pattern match includes a sequence of alternatives, each starting with the keyword case. - Each alternative includes a pattern and one or more expressions, which will be evaluated if the pattern matches. - An arrow symbol => separates the pattern from the expressions. - A match expression is evaluated by trying each of the patterns in the order they are written. The first pattern that matches is selected, and the part following the arrow is selected and executed.
  • 10. 1. Wildcard patterns The wildcard pattern ( _ ) matches any object whatsoever.It is used as a default.
  • 11. 2. Constant patterns A constant pattern matches only itself. Any literal may be used as a constant. For example, 5, true, and "hello" are all constant patterns. Also, any val or singleton object can be used as a constant.
  • 12.
  • 13. 3. Variable patterns A variable pattern matches any object, just like a Wildcard. The default case uses a variable pattern so that it has a name for the value, no matter what it is.
  • 14. 4. Constructor patterns A constructor pattern looks like : BinOp("+", Number(0) , Number(0)) It consists of a name BinOp and then a number of patterns within parenthese. Assuming the name designates a case class, such a pattern means to first check that the object is a member of the named case class, and then to check that the constructor parameters of the object match the extra patterns supplied.
  • 15.
  • 16. 5.Sequence patterns You can match against sequence types like List or Array just like you match against case classes. Use the same syntax, but now you can specify any number of elements within the pattern.
  • 17.
  • 18. 6. Tuple patterns You can match against tuples as well. A pattern like (a, b, c) matches an arbitrary 3-tuple.
  • 19. 7.Typed patterns You can use a typed pattern as a convenient replacement for type tests and type casts.
  • 20. Patterns in variable definitions Any time you define a val or a var, you can use a pattern instead of a simple identifier.
  • 21. Patterns in for expressions
  • 22. References Programming in Scala by Martin Odersky