Combine two match patterns in one

How (in a good way) two Scala match'es are combined?

First I need to check if the parameter is a valid value:

myOption match {
  case Some(op) =>
    doSomethingWith(op)
  case None =>
    handleTheError()

Then, if op was valid, I want to check out another pattern:

Path(request.path) match {
  case "work" => {
    println("--Let work--")

  }
  case "holiday" => {
    println("--Let relax--")
  }
  case _ => {
    println("--Let drink--")
  }
}

I could combine them as follows:

myOption match {
  case Some(op) =>
    doSomethingWith(op)
    Path(request.path) match {
      case "work" => {
        println("--Let work--")          
      }
      case "holiday" => {
        println("--Let relax--")
      }
      case _ => {
        println("--Let drink--")
      }
    }
  case None =>
    handleTheError()

But he feels sloppy. Is there a better way to combine them somehow.

Update

Sorry, I should have explained better. I am really trying to find out if there is a known scheme to simplify (or decompose) these control structures. For example (imagine this is true):

x match {
 case a => {
   y match {
    case c => {}
    case d => {}
   }
 }
 case b => {}
}

equally

x -> y match {
  case a -> c => {}
  case a -> d => {}
  case b => {}
}

I just wandered if someone already defined some refactoring patterns for the control flow, like algebra, where 2(x + y) = 2x + 2y

+5
source share
2 answers

You can do

myOption map { success } getOrElse handleTheError

scalaz,

myOption.cata(success, handleTheError)

success -

def success(op: Whatever) = {
  doSomethingWith(op)
  Path(request.path) match {
    case "work"    => println("--Let work--")
    case "holiday" => println("--Let relax--")
    case _         => println("--Let drink--")      
  }
}

Update

x -> y match {
  case a -> c => {}
  case a -> d => {}
  case b => {}
}

scala

(x, y) match {
  case (a, c) => {}
  case (a, d) => {}
  case (b, _) => {}
}

(, , , ), (c d ), ( a). , , map {} getOrElse {} - . , .

+9

(, ) , .. , match es, .

, :

x match {
 case a => {
   y match {
    case c => fooC(...)
    case d => fooD(...)
   }
 }
 case b => fooB(...)
}

:

(x,y) match {
  case (a, c) => fooC(...)
  case (a, d) => fooD(...)
  case (b, _) => fooB(...)
}

... y x.

+3

All Articles