0

For instance, I have two Try objects. I want to get error if one or another fails and process it in the same way:

  val t1 = Try(throw new Exception("one"))
  val t2 = Try(throw new Exception("two"))

  (t1, t2) match {
    case (Success(_), Success(_)) => println("It's ok")
    case _ : Failure(e), _) | (_, Failure(e) =>  // Compile error here

      println("Fail", e)                         // Doesn't matter from where e was come 
  }

Is it possible to make this code with the same e in both failure options compile?

Oleg
  • 899
  • 1
  • 8
  • 22
  • You can't- you can put the futures in a list and flatten it as in https://stackoverflow.com/questions/15495678/flatten-scala-try – Arnon Rotem-Gal-Oz Jun 28 '18 at 06:37
  • 1
    Is it so bad if you separate the two failing cases? `case (Failure(e), _) => println(s"Fail $e") case (_, Failure(e)) => println(s"Fail $e")` – mfirry Jun 28 '18 at 06:38
  • @mfirry Actually, not very bad, but I was wonder if it is possible. – Oleg Jun 28 '18 at 06:41

2 Answers2

5

You cannot combine match patterns this way. You can achieve the desired behaviour this way:

t1.flatMap(_ => t2) match {
   case Success(_) => println("It's ok")
   case Failure(e) => prinltn("Fail", e)
}
Nyavro
  • 8,806
  • 2
  • 26
  • 33
0

Another convinient way, based on the @Nyavro answer is to combine multiple tryes in a single try via for comprhensions:

 val tryDoIt = for {
   t1 <- Try(throw new Exception("one"))
   t2 <- Try(throw new Exception("two"))
   t3 <- Try(throw new Exception("three"))
 } yield (t1, t2, t3)

 tryDoIt match {
   case Success((x, y, z)) => println(x,y,z)
   case Failure(e) => println(e.getMessage)
 }
Oleg
  • 899
  • 1
  • 8
  • 22