Scala Option的收集方法不像我的PartialFunction

我想我错过了一些东西:
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})
为什么会发生这种错误?我想我误解了
collect
的作用......     
已邀请:
除非您指定,否则文字
None
的类型为
Option[Nothing]
。这是必要的,因为None必须是所有类型Option [_]的有效成员。如果你改写了
(None:Option[Int]) collect ({ case n if n > 0 => n + 1; case _ => 0}) 
要么
val x:Option[Int] = None
x collect ({ case n if n > 0 => n + 1; case _ => 0}) 
那么编译器就能输入检查你的收费电话     
None collect ({ case n if n > 0 => n + 1; case _ => 0}) 
为什么
n
>
的方法?那里没有任何东西允许编译器假设这一点。所以,尝试将其更改为:
None collect ({ case n: Int if n > 0 => n + 1; case _ => 0})
并且您将收到以下错误消息:
<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]
。     

要回复问题请先登录注册