Scala | unapplySeq() method
Last Updated :
08 Apr, 2019
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 :
object GfG
{
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
}
def main(args : Array[String]) =
{
val x = new Author
x match
{
case GfG(y : Int, _ ,z : String) =>
println( "The age of " +z+ " is: " +y)
}
x.age = 22
x.name = List( "Rahul" , "Nisha" )
x match
{
case GfG(y : Int, _ ,z : String) =>
println( "The age of " +z+ " is: " +y)
}
}
}
class Author
{
var age : Int = 24
var name : Seq[String] = List( "Rohit" , "Nidhi" )
}
|
Output:
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 :
object GfG
{
def main(args : Array[String])
{
object SortedSeq
{
def unapplySeq(x : Seq[Int]) =
{
if (x == x.sortWith( _ < _ ))
{
Some(x)
}
else None
}
}
val x = List( 1 , 2 , 3 , 4 , 5 )
x match
{
case SortedSeq(a, b, c, d,e) =>
println(List(a, c, e))
}
}
}
|
Here, we have used a function sortWith, that sorts the stated sequence as specified by the comparison function.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...