Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching MatchError at val initialisation with pattern matching in Scala?

Tags:

scala

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?

like image 661
Rogach Avatar asked Jan 18 '12 10:01

Rogach


4 Answers

Why not simply

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

?

like image 107
Kim Stebel Avatar answered Oct 19 '22 00:10

Kim Stebel


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.

like image 22
missingfaktor Avatar answered Oct 18 '22 23:10

missingfaktor


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
like image 22
ziggystar Avatar answered Oct 19 '22 00:10

ziggystar


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.

like image 40
david.perez Avatar answered Oct 18 '22 23:10

david.perez