What is the best way (concisest, clearest, idiomatic) to catch a MatchError
, when assigning values with pattern matching?
Example:
val a :: b :: Nil = List(1,2,3) // throws scala.MatchError
The best way I found so far:
val a :: b :: Nil = try {
val a1 :: b1 :: Nil = List(1,2,3)
List(a1, b1)
catch { case e:MatchError => // handle error here }
Is there an idiomatic way to do this?
Why not simply
val a::b::Nil = List(1,2,3) match {
case a1::b1::Nil => {
a1::b1::Nil
}
case _ => //handle error
}
?
Slightly improving on Kim's solution:
val a :: b :: Nil = List(1, 2, 3) match {
case x @ _ :: _ :: Nil => x
case _ => //handle error
}
If you could provide more information on how you might handle the error, we could provide you a better solution.
The following doesn't catch the error but avoids (some of; see Nicolas' comment) it. I don't know whether this is interesting to the asker.
scala> val a :: b :: _ = List(1,2,3)
a: Int = 1
b: Int = 2
The simple solution is this:
List(1, 2, 3) match {
case a :: b :: Nil => .....
case _ => // handle error
}
I don't like to match twice, because it is redundant. The "val" with pattern matching should only be used when you are sure it matches, or add a try /catch block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With