Scala模式匹配选项无有或没有绑定

Mik*_*yer 4 scala pattern-matching

我想做以下模式匹配:

minReachableInt match {
   case None | Some(n) if n <= 0 =>
     println("All positive numbers can be reached")
   case _ =>
     println("Not all positive numbers can be reached")
}
Run Code Online (Sandbox Code Playgroud)

当然,它不会编译,因为n不匹配None.但是,由于我在后续代码中不需要它,如何在不重复代码的情况下以您能想象的最美丽的方式实现我的结果?

Ben*_*mes 10

使用模式匹配语法可以做什么是有限的,所以不要试图用它来表达你的所有逻辑.

这个问题可以表达为filter:

minReachableInt filter (_ <= 0) match {
  case None =>
    println("All positive numbers can be reached")
  case _ =>
    println("Not all positive numbers can be reached")
}
Run Code Online (Sandbox Code Playgroud)