Scala萃取器

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()方法检查是否通过了学生并根据结果将其删除。

翻译自: https://www.includehelp.com/scala/extractors.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值