Home » Scala language

Scala Extractors

In Scala, extractors are objects have special methods. In this tutorial, we will learn about extractors in Scala in detail with working and examples.
Submitted by Shivang Yadav, on March 08, 2020

Scala | Extractors

An extractor is a special type of object that has some special methods. These methods are: apply() and 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.
  • 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.

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.

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.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.