Pattern matching simplification


#1

Let’s say, I have the following code snippet:

val num = Future.successful(10)

num map {
  case n if n > 0 => // do something
  case _             // do something
}

My question is: can I simplify case n if n > 0 somehow?

I expected that I can write something like:

case _ > 0 => // do something

or with explicitly specified type (although we know that Future has inferred type [Int]):

case _: Int > 0 => // do something

Can this code be simplified somehow?
If not, is it possible to introduce such feature in newer Scala versions?


#2

Yes, it’s possible to define a custom pattern matcher so you can say:

case Positive(n) => ...

You would do this by writing a Positive object with an unapply method that checks and returns Some n if n is positive and None otherwise.


#3

Thank you. Seems to be very interesting. Remains only to convince my team :joy:


#4

Personally I wouldn’t do this, case n if n ... => ... is simple enough and still pretty elegant :slight_smile:


#5

Wow! Really a good and interesting idea! Though it might be hard to
maintain. LOL


#6

If you like underscores, here’s a fun one.

num map (_ > 0) map (if(_) "ok" else "nok")

#7

That seems to work how I’d expect, although you could also use operator sectioning to make it even more fun:

num map (0.<) map (if (_) "ok" else "nok")