简体   繁体   中英

Scala: simplify case with comparison

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 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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM