Deconstructor unapply does not work this way at all. It takes only one argument, the matched value, and returns an option on a tuple, with as many elements as there are arguments to the your pattern (NPlusK). That is, when you have
(n: Int) match {
...
case NPlusK(n, 1)
It will look for an unapply
method with an Int
(or supertype) argument. If there is such a method, and if the return type is a Tuple2
(as NPlusK appears with two arguments in the pattern), then it will try to match. Whatever subpattern there are inside NPlusK (here the variable n, and the constant 1), will not be passed to unapply in anyway (what do you expect if you write case NPlusK(NPlusK(1, x), NPlusK(1, y))
?). Instead, if unapply returns some tuple, then each element of the tuple will be matched to the corresponding subpattern, here n
which always matches, and 1 which will match if the value is equal to 1.
You could write
def unapply(n: Int) = if (n > 0) Some((n-1, 1)) else None.
That would match when your NPlusK(n, 1)
. But that would not match NPlusK(n, 2)
, nor NPlusK(1, n)
(except if n
is 2). This does not make much sense. A pattern should probably have only one possible match. NPlusK(x, y)
can match n
in many different ways.
What would work would be something Peano integers like, with Succ(n)
matching n+1
.