Scala | unapplySeq() method
The unapplySeq() method is an Extractor method. It extracts an Object of particular type and then again reconstructs it into a Sequence of extracted values and the length of this Sequence is not specified at the time of compilation. So, in order to reconstruct an Object that contains a Sequence, you need to utilize this unapplySeq method.
Syntax:
def unapplySeq(object: X): Option[Seq[T]]
Here, we have an object of type X and this method either returns None, when the object does not match or returns a Sequence of extracted values of type T, enclosed in class Some.
Now, lets understand it through some examples.
Example :
// Scala program of unapplySeq // method // Creating object object GfG { // Defining unapplySeq method def unapplySeq(x : Any) : Option[Product 2 [Int,Seq[String]]] = { val y = x.asInstanceOf[Author] if (x.isInstanceOf[Author]) { Some(y.age, y.name) } else None } // Main method def main(args : Array[String]) = { // Creating object for Author val x = new Author // Applying Pattern matching x match { case GfG(y : Int, _ ,z : String) => // Displays output println( "The age of " +z+ " is: " +y) } // Assigning age and name x.age = 22 x.name = List( "Rahul" , "Nisha" ) // Again applying Pattern matching x match { case GfG(y : Int, _ ,z : String) => //Displays output println( "The age of " +z+ " is: " +y) } } } // Creating class for author class Author { // Assigning age and name var age : Int = 24 var name : Seq[String] = List( "Rohit" , "Nidhi" ) } |
The age of Nidhi is: 24 The age of Nisha is: 22
Here, we have used a trait Product2 in the Option in order to pass two arguments to it. Product2 is a Cartesian product of two elements.
Example :
// Scala program of using //'UnapplySeq' method of // Extractors // Creating object object GfG { // Main method def main(args : Array[String]) { object SortedSeq { // Defining unapply method def unapplySeq(x : Seq[Int]) = { if (x == x.sortWith( _ < _ )) { Some(x) } else None } } // Creating a List val x = List( 1 , 2 , 3 , 4 , 5 ) // Applying pattern matching x match { case SortedSeq(a, b, c, d,e) => // Displays output println(List(a, c, e)) } } } |
List(1, 3, 5)
Here, we have used a function sortWith, that sorts the stated sequence as specified by the comparison function.