开发者

Scala contiguous match

开发者 https://www.devze.com 2022-12-26 14:41 出处:网络
pathTokens match { case开发者_高级运维 List(\"post\") => (\"post\", \"index\") case List(\"search\") => (\"search\", \"index\")
pathTokens match {
 case开发者_高级运维 List("post") => ("post", "index")
 case List("search") => ("search", "index")
 case List() => ("home", "index")
} match {
 case (controller, action) => loadController(http, controller, action)
 case _ => null
}

I wanted contiguous match. but got compile error. :(

(pathTokens match {
 case List("post") => ("post", "index")
 case List("search") => ("search", "index")
 case List() => ("home", "index")
}) match {
 case (controller, action) => loadController(http, controller, action)
 case _ => null
}

When I wrapped first match with parenparenthesis, it worked ok. Why I need parenthesis here ?


Unfortunately, that's how the Scala syntax is defined. Please have a look at the specification:
http://www.scala-lang.org/docu/files/ScalaReference.pdf

There you will find the following definition (p. 153, shortened for clarity):

Expr1 ::= PostfixExpr 'match' '{' CaseClauses '}'

If you dig into PostfixExpr you will eventually find SimpleExpr1 which contains the following definition:

SimpleExpr1 ::= '(' [Exprs [',']] ')'
Exprs ::= Expr {',' Expr}

That means that SimpleExpr1 (and thus PostfixExpr) can only contain other expressions (like 'x match y') when they are wrapped in parentheses.


Not what you want, but you can do stuff like this:

val f1 = (_: List[String]) match {
 case List("post") => ("post", "index")
 case List("search") => ("search", "index")
 case List() => ("home", "index")
}

val f2 = (_: (String, String)) match {
 case (controller, action) => loadController(http, controller, action)
}

(f1 andThen f2)(pathTokens)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号