4

我想做以下模式匹配:

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")
}

当然,它不会编译,因为 n 在None. 但是由于我在后续代码中不需要它,我怎样才能在不复制代码的情况下以你能想象的最漂亮的方式实现我的结果?

4

1 回答 1

10

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

这个问题可以用以下方式表达filter

minReachableInt filter (_ <= 0) match {
  case None =>
    println("All positive numbers can be reached")
  case _ =>
    println("Not all positive numbers can be reached")
}
于 2012-12-19T11:07:54.677 回答