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>
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With