What's the reasoning behind adding the “case” keyword to Scala?

后端 未结 4 1100
臣服心动
臣服心动 2021-02-13 09:57

Apart from:

case class A

... case which is quite useful?

Why do we need to use case in match? Wouldn

4条回答
  •  一生所求
    2021-02-13 10:32

    The second issue, anonymous functions that avoid the case, is a matter of debate:

    https://groups.google.com/d/msg/scala-debate/Q0CTZNOekWk/z1eg3dTkCXoJ

    Also: http://www.scala-lang.org/old/node/1260

    For the first issue, the choice is whether you allow a block or an expression on the RHS of the arrow.

    In practice, I find that shorter case bodies are usually preferable, so I can certainly imagine your alternative syntax resulting in crisper code.

    Consider one-line methods. You write:

    def f(x: Int) = 2 * x
    

    then you need to add a statement. I don't know if the IDE is able to auto-add parens.

    def f(x: Int) = { val res = 2*x ; res }
    

    That seems no worse than requiring the same syntax for case bodies.

    To review, a case clause is case Pattern Guard => body.

    Currently, body is a block, or a sequence of statements and a result expression.

    If body were an expression, you'd need braces for multiple statements, like a function.

    I don't think => results in ambiguities since function literals don't qualify as patterns, unlike literals like 1 or "foo".

    One snag might be: { case foo => ??? } is a "pattern matching anonymous function" (SLS 8.5). Obviously, if the case is optional or eliminated, then { foo => ??? } is ambiguous. You'd have to distinguish case clauses for anon funs (where case is required) and case clauses in a match.

    One counter-argument for the current syntax is that, in an intuition deriving from C, you always secretly hope that your match will compile to a switch table. In that metaphor, the cases are labels to jump to, and a label is just the address of a sequence of statements.

    The alternative syntax might encourage a more inlined approach:

    x match {
      C => c(x)
      D => d(x)
      _ => ???
    }
    @inline def c(x: X) = ???
    //etc
    

    In this form, it looks more like a dispatch table, and the match body recalls the Map syntax, Map(a -> 1, b -> 2), that is, a tidy simplification of the association.

提交回复
热议问题