I am kind of confused about extractor and its using. I read Scala document and meet that one
object Twice {
def apply(x: Int): Int = x * 2
def unapply(z: Int): Option[Int] = if (z%2 == 0) Some(z/2) else None
}
object TwiceTest extends App {
val x = Twice(21) // x = 42
x match { case Twice(n) => Console.println(n) } // prints 21
}`
As the above code print out, when we call x match {case Twice(n) ...
, it means Twice(n)
--> Twice.unapply(n)
--> Twice.unapply(42)
and get Some(n/2)
--> Some(42/2)
and plug result into n
again, print out 21
If I change "unapply" as follow:
def unapply(z: Int): Option[Int] = if (z%2 == 0) Some(z - 2) else None
What I get from the console is 40
So, do I understand it right?