Scala Option collection method dislikes my PartialFunction

I think something is missing:

scala> Some(1) collect ({ case n if n > 0 => n + 1; case _ => 0})
res0: Option[Int] = Some(2)

scala> None collect ({ case n if n > 0 => n + 1; case _ => 0})   
<console>:6: error: value > is not a member of Nothing
       None collect ({ case n if n > 0 => n + 1; case _ => 0})
                                 ^
<console>:6: error: value + is not a member of Nothing
       None collect ({ case n if n > 0 => n + 1; case _ => 0})

Why is this error occurring? I think I don’t understand how it works collect...

+3
source share
2 answers

If you do not specify, the letter Noneis of type Option[Nothing]. This is necessary because None must be a full member of all Option [_] types. If you wrote instead

(None:Option[Int]) collect ({ case n if n > 0 => n + 1; case _ => 0}) 

or

val x:Option[Int] = None
x collect ({ case n if n > 0 => n + 1; case _ => 0}) 

then the compiler will be able to dial a test of your call to collect

+13
source
None collect ({ case n if n > 0 => n + 1; case _ => 0}) 

Why nhas a method >? There is nothing to allow the compiler to suggest this. So try changing this to:

None collect ({ case n: Int if n > 0 => n + 1; case _ => 0})

And you will get the following error message:

<console>:8: error: pattern type is incompatible with expected type;
 found   : Int
 required: Nothing
       None collect ({ case n: Int if n > 0 => n + 1; case _ => 0}) 
                               ^

, , , Int, , None. , None Option[Nothing].

+1

Source: https://habr.com/ru/post/1796107/


All Articles