Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I have to return Some in unapply method

Tags:

scala

Why the following code doesn't work if I do not use Some in unapply method?

scala> object T {
     | def unapply(i:Int) = (i+1,i+2) //Some not used, I get error
     | }
defined object T

scala> 1 match {
     | case T(x,y) => println(x,y)
     | }
<console>:14: error: an unapply result must have a member `def isEmpty: Boolean
       case T(x,y) => println(x,y)
            ^

scala> object T {
     | def unapply(i:Int) = Some(i+1,i+2) //Some used. No error
     | }
defined object T

scala> 1 match {
     | case T(x,y) => println(x,y)
     | }
(2,3)

scala>

like image 541
Manu Chadha Avatar asked Dec 14 '22 20:12

Manu Chadha


1 Answers

You don't. You have to return something that has an isEmpty() method and a get() method. Option provides both so that's a convenient solution.

This is how the compiler knows that the match has succeeded. If isEmpty() returns true then the match fails and the next match is attempted (if there is a next).

like image 95
jwvh Avatar answered Dec 21 '22 10:12

jwvh