gpt4 book ai didi

Scala 模式匹配选项 None 有或没有绑定(bind)

转载 作者:行者123 更新时间:2023-12-04 19:31:44 26 4
gpt4 key购买 nike

我想做以下模式匹配:

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

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

最佳答案

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

这个问题可以用 filter 来表达。 :

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

关于Scala 模式匹配选项 None 有或没有绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13950650/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com