Rogach
Rogach

Reputation: 27200

Catching MatchError at val initialisation with pattern matching in 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?

Upvotes: 8

Views: 2165

Answers (4)

david.perez
david.perez

Reputation: 7012

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.

Upvotes: 1

ziggystar
ziggystar

Reputation: 28680

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

Upvotes: 1

missingfaktor
missingfaktor

Reputation: 92046

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.

Upvotes: 6

Kim Stebel
Kim Stebel

Reputation: 42047

Why not simply

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

?

Upvotes: 7

Related Questions