Scala: simplify case with comparison

Viewed 130

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?

2 Answers

If you want to simplify the guard, you can filter the Future a priori:

val num = Future.successful(10).filter(_ > 0).map { nat =>
}

Otherwise, you can keep the guard and use Future.collect:

val num = Future.successful(10).collect {
    case n if n > 0 => // do something
}

One important thing to note is that if the partial function is not defined for the value which returned (i.e for your case -1) then the resulting future will be a Failure containing a NoSuchElementException.

Other than these options, you'll need the guard. I don't see any syntactically shorter way to express it.

You can't simplify case n if n > 0 => ....

Every case clause in a pattern match needs to have a pattern and (optionally) a guard.

The syntax you are referring to (_ > 0) is only valid in lambdas, but there's no similar special syntax for case clauses.

Related