Reputation: 10710
I would like to do the following 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")
}
Of course, it does not compile, because n is not matched in None
. But as I don't need it in the subsequent code, how can I achieve my result without duplicating the code, in the most beautiful way you could imagine ?
Upvotes: 4
Views: 328
Reputation: 125307
There are limits to what you can do with pattern matching syntax, so don't try to use it to express all your logic.
This problem could be expressed using filter
:
minReachableInt filter (_ <= 0) match {
case None =>
println("All positive numbers can be reached")
case _ =>
println("Not all positive numbers can be reached")
}
Upvotes: 10