Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala pattern matching option None with or without binding

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 ?

like image 987
Mikaël Mayer Avatar asked Dec 26 '22 12:12

Mikaël Mayer


1 Answers

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")
}
like image 93
Ben James Avatar answered Jan 31 '23 09:01

Ben James