Catching MatchError on val initialization matching patterns in Scala?

What is the best way (concisest, clearest, idiomatic) to catch MatchError when assigning values ​​using pattern matching?

Example:

 val a :: b :: Nil = List(1,2,3) // throws scala.MatchError 

The best way I've 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?

+4
source share
4 answers

Kim's solution improved slightly:

 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 can handle this error, we could provide you with a better solution.

+6
source

Why not just

 val a::b::Nil = List(1,2,3) match { case a1::b1::Nil => { a1::b1::Nil } case _ => //handle error } 

?

+7
source

The following error is not resolved, but avoids (some of them, see Nicholas's comment). I do not know if this is interesting to the interested person.

 scala> val a :: b :: _ = List(1,2,3) a: Int = 1 b: Int = 2 
+1
source

A simple solution is the following:

 List(1, 2, 3) match { case a :: b :: Nil => ..... case _ => // handle error } 

I do not like the coincidence twice because it is redundant. "Val" with pattern matching should only be used when you are sure it matches, or you add a try / catch block.

0
source

Source: https://habr.com/ru/post/1391614/


All Articles