Latest web development tutorials

Scala extractor (Extractor)

Extractor is configured to extract the parameters of the object passed to it from the object.

Scala standard library contains a number of predefined extractor, we'll look at them roughly.

Scala is an object extraction method with a unapply of. unapply method regarded apply methods reverse: unapply accepts an object and extract values ​​from the object, the value of the extracted value is usually used to construct the object.

The following example demonstrates the extraction object mail address:

object Test {
   def main(args: Array[String]) {
      
      println ("Apply 方法 : " + apply("Zara", "gmail.com"));
      println ("Unapply 方法 : " + unapply("[email protected]"));
      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
      }
   }
}

Implementation of the above code, the output is:

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

The above object defines twomethods: apply and unapplymethods. We do not need to apply the method by using the new operator to create objects. So you can construct a string "[email protected]" by the statement Test ( "Zara", "gmail.com").

unapply method regarded apply methods reverse: unapply accepts an object and extract values ​​from the object, the value of the extracted value is usually used to construct the object. Examples of the method we use to extract suffix Unapply user name and e-mail addresses from the object.

The unapply method returns None in incoming e-mail address instead of a string instance. The following code demonstrates:

unapply("[email protected]") 相等于 Some("Zara", "gmail.com")
unapply("Zara Ali") 相等于 None

Uses pattern matching extraction

When we instantiate a class, you can take zero or more parameters, the compiler is invoked when an instance of the apply method. We can define and apply the method in the class object.

As we mentioned before, unapply used to extract the value we specify to find, on the contrary it apply operation. When we use the match statements in the extraction object is, unapply will be performed automatically, as follows:

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
}

Implementation of the above code, the output is:

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