Extractor (Extractor)
We have previously used the scala very powerful pattern matching capabilities, and by pattern matching, we can quickly match the sample class member variables.
E.g:
// 1. 创建两个样例类
case class Person(name:String, age:Int)
case class Order(id:String)
def main(args: Array[String]): Unit = {
// 2. 创建样例类对象,并赋值为Any类型
val zhangsan:Any = Person("张三", 20)
val order1:Any = Order("001")
// 3. 使用match...case表达式来进行模式匹配
// 获取样例类中成员变量
order1 match {
case Person(name, age) => println(s"姓名:${name} 年龄:${age}")
case Order(id1) => println(s"ID为:${id1}")
case _ => println("未匹配")
}
}
That is not all classes can be such a pattern matching it? The answer is:
no. To support pattern matching, it must implement a extractor.
Define extractor
before we learned, and apply the method to achieve companion object class, you can use the class name to quickly build an object. Companion object, there is a unapply method. And apply contrast, unapply the object class for the dismantling of one element
to implement a class of the extractor, need only to implement a method in unapply associated objects of this class.
Syntax:
def unapply(stu:Student):Option[(类型1, 类型2, 类型3...)] = { if(stu != null) { Some((变量1, 变量2, 变量3...)) } else { None } }
Example
example illustrates
create a Student class that contains the name, age two fields
to achieve a class destructor, and expression pattern matching using the match to extract class field.
Reference Code:
class Student(var name:String, var age:Int)
object Student {
def apply(name:String, age:Int) = {
new Student(name, age)
}
def unapply(student:Student) = {
val tuple = (student.name, student.age)
Some(tuple)
}
}
def main(args: Array[String]): Unit = {
val zhangsan = Student("张三", 20)
zhangsan match {
case Student(name, age) => println(s"${name} => ${age}")
}
}
result: