Reputation: 941
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?
Upvotes: 0
Views: 75
Reputation: 941
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)
}
Upvotes: 0
Reputation: 8866
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)
}
Upvotes: 5