I think I'm missing something:
scala> S开发者_StackOverflow中文版ome(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...
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
None collect ({ case n if n > 0 => n + 1; case _ => 0})
Why would n
have the method >
? There's nothing in there to allow the compiler to assume that. So, try changing that to:
None collect ({ case n: Int if n > 0 => n + 1; case _ => 0})
And you'll 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})
^
Meaning, basically, that the compiler knows an Int
is impossible here, since you are just passing None
. As it happens, None
is of type Option[Nothing]
.
精彩评论