scalacollectscala-optionpartialfunction

Scala Option's collect method doesn't like my PartialFunction


I think I'm missing something:

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 happening? I think I'm misunderstanding how collect works...


Solution

  • Unless you specify, the literal None is of type Option[Nothing]. This is necessary, since None has to be a valid member of all types Option[_]. If you instead wrote

    (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 would be able to type check your collect call