Home:ALL Converter>Catching MatchError at val initialisation with pattern matching in Scala?

Catching MatchError at val initialisation with pattern matching in Scala?

Ask Time:2012-01-18T18:40:45         Author:Rogach

Json Formatter

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?

Author:Rogach,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/8908707/catching-matcherror-at-val-initialisation-with-pattern-matching-in-scala
ziggystar :

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.\n\nscala> val a :: b :: _ = List(1,2,3)\na: Int = 1\nb: Int = 2\n",
2012-01-18T12:03:37
Kim Stebel :

Why not simply\n\nval a::b::Nil = List(1,2,3) match {\n case a1::b1::Nil => {\n a1::b1::Nil\n }\n case _ => //handle error\n}\n\n\n?",
2012-01-18T11:17:31
missingfaktor :

Slightly improving on Kim's solution:\n\nval a :: b :: Nil = List(1, 2, 3) match {\n case x @ _ :: _ :: Nil => x\n case _ => //handle error\n}\n\n\nIf you could provide more information on how you might handle the error, we could provide you a better solution.",
2012-01-18T13:58:14
yy