English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Scala Extractors (Extractors)

Extractor extracts the parameters used to construct the object from the object passed to it.

Scala standard library includes some predefined extractors, and we will get a brief understanding of them.

Scala extractor is an object with an unapply method. The unapply method is the reverse operation of the apply method: unapply accepts an object, then extracts values from the object, and the extracted values are usually used to construct the values of the object.

The following example demonstrates the email address extractor object:

object Test {
   def main(args: Array[String]) {
      
      println("Apply method: ", + apply("Zara", "gmail.com"));
      println("Unapply method: ", + unapply("[email protected]"));
      println("Unapply method: ", + unapply("Zara Ali"));
   }
   // Injection method (optional)
   def apply(user: String, domain: String) = {
      user +"@"+ domain
   }
   // Extraction method (required)
   def unapply(str: String): Option[(String, String)] = {
      val parts = str.split("@")
      if (parts.length == 2{
         Some(parts(0), parts(1)) 
      }
         None
      }
   }
}

Execute the above code, the output will be:

$ scalac Test.scala 
$ scala Test
Apply method: [email protected]
Unapply method: Some((Zara,gmail.com))
Unapply method: None

The above object defines two methods: apply and unapply method. Through the apply method, we can create an object without using the new operation. Therefore, you can construct the string "[email protected]" using the statement Test("Zara", "gmail.com").

The unapply method is the reverse operation of the apply method: unapply accepts an object, then extracts values from the object, and the extracted values are usually used to construct the values of the object. In the example, we use The unapply method extracts the username and the suffix of the email address from the object.

The unapply method returns None when the input string is not an email address. The code demonstration is as follows:

unapply("[email protected]") is equivalent to Some("Zara", "gmail.com")
unapply("Zara Ali") is equivalent to None

Extractor Uses Pattern Matching

When we instantiate a class, we can pass 0 or more parameters, and the compiler will call the apply method when instantiating. We can define the apply method in both classes and objects.

As we mentioned earlier, unapply is used to extract the values we specify to search for, and it is the opposite operation of apply. When we use the match statement in the extractor object, unapply will automatically execute, as shown below:

object Test {
   def main(args: Array[String]) {
      
      val x = Test(5)
      println(x)
      x match
      {
         case Test(num) => println(x + " is " + num + " twice!")
         //unapply is called
         case _ => println("Unable to calculate")
      }
   }
   def apply(x: Int) = x*2
   def unapply(z: Int): Option[Int] = if (z%2==0) Some(z/2) else None
}

Execute the above code, the output will be:

$ scalac Test.scala 
$ scala Test
10
10 is 5 twice!