Scala | 提取器 (Scala | Extractors)
An extractor is a special type of object that has some special methods. These methods are: apply() and unapply().
提取器是一种特殊的对象,具有一些特殊的方法。 这些方法是: apply()和unapply() 。
The apply() method of extractor object is used to feeding values for the object, it takes parameter values, formats them and adds them to the object.
提取器对象的apply()方法用于馈送对象的值,它获取参数值,对其进行格式化并将其添加到对象中。
The unapply() method of extractor object is used to delete values from the object, it matches the value and removes them from the object list.
提取器对象的unapply()方法用于从对象中删除值,它匹配该值并将其从对象列表中删除。
抽气机的工作 (Working of extractors)
Let's take an example of an object that apply() as well as unapply() method. The apply() method takes arguments and adds them to class. The unapply() does the exact opposite, it takes arguments, matches them and then deletes, i.e. deconstructs.
让我们举一个apply()对象以及unapply()方法的示例。 apply()方法接受参数并将其添加到类中。 unapply()的作用恰恰相反,它接受参数,将其匹配,然后删除,即解构。
Program:
程序:
object Student
{
def main(args: Array[String])
{
def apply(name: String, result: String) =
{
name +" is "+ result
}
def unapply(x: String): Option[(String, String)] =
{
val y = x.split("is")
if (y.length == 2 && y(1)=="Pass")
{
Some(y(0), y(1))
}
else
None
}
println ("The Apply method returns : " +
apply("Ram", "Pass"))
println ("The Unapply method returns : " +
unapply("RamisPass"))
}
}
Output
输出量
The Apply method returns : Ram is Pass
The Unapply method returns : Some((Ram,Pass))
Explanation:
说明:
The unapply() method here, checking if the student is passed and removes it based on the result.
这里的unapply()方法检查是否通过了学生并根据结果将其删除。