Scala Extractor


The extractor extracts the parameters used to construct the object from the object passed to it.

The Scala standard library contains some predefined extractors, we will take a look at them briefly.

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

The following example demonstrates the extractor object of the email address:

object Test {
   def main(args: Array[String]) {
      
      println ("Apply 方法 : " + apply("Zara", "gmail.com"));
      println ("Unapply 方法 : " + unapply("Zara@gmail.com"));
      println ("Unapply 方法 : " + unapply("Zara Ali"));

   }
   // 注入方法 (可选)
   def apply(user: String, domain: String) = {
      user +"@"+ domain
   }

   // 提取方法(必选)
   def unapply(str: String): Option[(String, String)] = {
      val parts = str split "@"
      if (parts.length == 2){
         Some(parts(0), parts(1)) 
      }else{
         None
      }
   }
}

Execute the above code, the output result is:

$ scalac Test.scala 
$ scala Test
Apply 方法 : Zara@gmail.com
Unapply 方法 : Some((Zara,gmail.com))
Unapply 方法 : None

The above object defines two methods: apply and unapply methods. With the apply method we can create objects without using the new operation. So you can construct a string "Zara@gmail.com" through the statement Test("Zara", "gmail.com").

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

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

unapply("Zara@gmail.com") 相等于 Some("Zara", "gmail.com")
unapply("Zara Ali") 相等于 None

The extractor uses pattern matching

When we instantiate a class, we can bring 0 or more parameters, and the compiler will instantiate it The apply method will be called. We can define apply method in both classes and objects.

As we mentioned before, unapply is used to extract the value we specify to find, which is the opposite of apply. When we use the match statement in the extractor object, unapply will be executed automatically, as shown below:

object Test {
   def main(args: Array[String]) {
      
      val x = Test(5)
      println(x)

      x match
      {
         case Test(num) => println(x + " 是 " + num + " 的两倍!")
         //unapply 被调用
         case _ => println("无法计算")
      }

   }
   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 result is:

$ scalac Test.scala 
$ scala Test
10
10 是 5 的两倍!