Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala

What are Extractor Objects in Scala?

Behzad Ahmad

An extractor is an object that includes the unapply method. We use this to extract the attributes from an object and return its initial attributes. We use the unapply method to match a value and take it apart, as opposed to the apply method which takes arguments and creates an object out of those arguments.

Return type

The return type must be as follows:

  • If we want to check something as either true or false, then the function will return a Bool.

  • If we want to return multiple sub-values A1 to An, then we group them in the optional tuple Option[(A1,...,An)].

Code

object temp
{
  def main(args: Array[String])
  {
    def unapply(x:Int): Boolean = {
      if (x % 2 == 0)
        true
      else
        false
    }
    println ("Return : " + unapply(20))
    println ("Return  : " + unapply(71))
    
  }
}

Output

Return : true
Return : false
object temp
{ 
    def main(args:Array[String])
    {
      val ptr = List(5, 2, 9)
      
      val result = ptr.apply(0)
        
      println(result)  
    }
}

Output

5

Explanation

In this example, the object temp defines a method unapply. A parameter is passed to unapply.

If the value is divided by 2, then it returns true. Otherwise, it returns false.

RELATED TAGS

scala

CONTRIBUTOR

Behzad Ahmad
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring