An extractor
is an object that includes the unapply
method. We use this to extract the attributes from an object and return its initial attributes. We use the unapply
method to match a value and take it apart, as opposed to the apply
method which takes arguments and creates an object out of those arguments.
The return type must be as follows:
If we want to check something as either true
or false
, then the function will return a Bool
.
If we want to return multiple sub-values A1 to An, then we group them in the optional tuple Option[(A1,...,An)]
.
object temp{def main(args: Array[String]){def unapply(x:Int): Boolean = {if (x % 2 == 0)trueelsefalse}println ("Return : " + unapply(20))println ("Return : " + unapply(71))}}
Return : true
Return : false
object temp{def main(args:Array[String]){val ptr = List(5, 2, 9)val result = ptr.apply(0)println(result)}}
5
In this example, the object temp
defines a method unapply
. A parameter is passed to unapply
.
If the value is divided by 2, then it returns true. Otherwise, it returns false.
Free Resources