Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
Scala String replaceFirst() method with example
Next article icon

Using Extractors with Pattern Matching In Scala

Last Updated : 02 Aug, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

Scala Extractor is defined as an object which has a method named unapply as one of its part. Extractors can be utilized in Pattern Matching. The unapply method will be executed spontaneously, While comparing the Object of an Extractor in Pattern Matching.

Below is the example of Extractor with pattern matching.
Example #1:




// Scala program of extractors 
// with pattern matching 
  
// Creating object 
object GfG 
{ 
  
    // Main method 
    def main(args: Array[String]) 
    { 
  
        // Assigning value to the 
        // object 
        val x = GfG(25) 
  
        // Displays output of the 
        // Apply method 
        println(x) 
  
        // Applying pattern matching 
        x match
        { 
  
            // unapply method is called 
            case GfG(y) => println("The value is: "+y) 
            case _ => println("Can't be evaluated") 
      
        } 
    } 
      
    // Defining apply method 
    def apply(x: Double) = x / 5
  
    // Defining unapply method 
    def unapply(z: Double): Option[Double] =
  
        if (z % 5 == 0) 
        { 
            Some(z/5) 
        } 
      
        else None 
} 
 
 
Output:
  5.0  The value is: 1.0  

In above example, object name is GFG also we are using unapply method and applying case class with match expression.

Example #2:




// Scala program of extractors 
// with pattern matching 
  
// Creating object 
object GFG
{ 
  
    // Main method 
    def main(args: Array[String]) 
    { 
  
        val x = GFG(15)
        println(x)
  
        x match
        {
            case GFG(num) => println(x + 
                        " is bigger two times than " + num)
          
            // Unapply is invoked
            case _ => println("not calculated")
    }
}
def apply(x: Int) = x * 2
def unapply(z: Int): Option[Int] = if (z % 2 == 0) 
                                    Some(z/2) else None
} 
 
 
Output:
  30  30 is bigger two times than 15  

When comparing an extractor object using the match statement the unapply method will be automatically executed.
Note: A Case class already has an Extractor in it so, it can be utilized spontaneously with Pattern Matching.



Next Article
Scala String replaceFirst() method with example

D

DivyaPareek
Improve
Article Tags :
  • Scala

Similar Reads

  • Scala String regionMatches() method with example
    The regionMatches() method is used to check if two string regions are equal or not. However, if ignoreCase is stated true in the argument list then the case difference is ignored. Method Definition: Boolean regionMatches(boolean ignoreCase, int toffset, String other, int offset, int len) Return Type
    1 min read
  • Scala | Pattern Matching
    Pattern matching is a way of checking the given sequence of tokens for the presence of the specific pattern. It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C. Here, "match" keyword is used inste
    3 min read
  • Scala String matches() method with example
    The matches() method is used to check if the string stated matches the specified regular expression in the argument or not. Method Definition: Boolean matches(String regex) Return Type: It returns true if the string matches the regular expression else it returns false. Example #1: // Scala program o
    1 min read
  • Scala String replaceFirst() method with example
    The replaceFirst() method is same as replaceAll but here only the first appearance of the stated sub-string will be replaced. Method Definition: String replaceFirst(String regex, String replacement) Return Type: It returns the stated string after replacing the first appearance of stated regular expr
    1 min read
  • Scala String replaceAll() method with example
    The replaceAll() method is used to replace each of the stated sub-string of the string which matches the regular expression with the string we supply in the argument list. Method Definition: String replaceAll(String regex, String replacement) Return Type: It returns the stated string after replacing
    1 min read
  • Scala Iterator mkString() method with example
    The mkString() method belongs to the concrete value member of the class Abstract Iterator. It is utilized to display all the elements of the collection in a string. Method Definition: val result = iter.mkString Here, we are storing string in result variable. Return Type: It returns the string repres
    1 min read
  • Scala - String Methods with Examples
    In Scala, as in Java, a string is a sequence of characters. In Scala, objects of String are immutable which means a constant and cannot be changed once created. In the rest of this section, we discuss the important methods of java.lang.String class. char charAt(int index): This method is used to ret
    12 min read
  • Using anonymous functions with the map method in Scala
    In Scala, you can use anonymous functions with map method. And here we will discuss the usage of multiple line anonymous functions with map. Therefore, whenever you see that your algorithm is becoming lengthy then instead of utilizing an anonymous function you can firstly define the method and then
    2 min read
  • Scala Iterator seq() method with example
    The seq() method belongs to the concrete value members of the class Iterable. It is helpful in visualizing the sequential view of the stated collection. It has a time complexity of O(1). Method Definition: def seq: Iterator[A] Return Type: It returns a sequential view of the iterator. Example : // S
    1 min read
  • Scala List iterator() method with example
    The iterator method is utilized to give an iterator. Method Definition: def iterator: Iterator[A] Return Type: It returns a non-empty iterator for non-empty list and returns an empty iterator for empty list. Example #1: // Scala program of iterator // method // Creating object object GfG { // Main m
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences