Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 561
pr1001 Avatar asked Dec 07 '22 22:12

pr1001


1 Answers

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

like image 81
Dave Griffith Avatar answered Feb 23 '23 13:02

Dave Griffith