Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a full specification for pattern matching possibilities of Scala?

Is there a full specification for pattern matching possibilities of Scala?

I am unable to fix following code:

  something match {
    case e @ (sae: ServerApiException if sae.statusCode == 401 | _: UnauthorizedException) => {
      doSomething(e)
    }
    ...
  }

(It does not compile in 2.8.1.)

like image 274
TN. Avatar asked Dec 22 '22 11:12

TN.


1 Answers

I'm not sure I'd write the code this way; it's hard to follow (in addition to not working in its original form).

I'd rather go for something like

def doSomething(e: Exception) = { /* whatever */ }
something match {
  case sae: ServerApiException if (sae.statusCode == 401) => doSomething(sae)
  case ue: UnauthorizedException => doSomething(ue)
}

to avoid duplicate code. Or you could use options:

(something match {
  case sae: ServerApiException if (sae.statusCode == 401) => Some(sae)
  case ue: UnauthorizedException => Some(ue)
  case _ => None
}).foreach(e => /* do something */ )

if you prefer to write the method afterwards. But I think the first way is likely the clearest.

like image 165
Rex Kerr Avatar answered Dec 25 '22 22:12

Rex Kerr