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

后端 未结 4 1090
臣服心动
臣服心动 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:44

    First, as we know, it is possible to put several statements for the same case scenario without needing some separation notation, just a line jump, like :

    x match {
           case y if y > 0 => y * 2
                              println("test")
                              println("test2")  // these 3 statements belong to the same "case"
    }
    

    If case was not needed, compiler would have to find a way to know when a line is concerned by the next case scenario.

    For example:

    x match {
       y if y > 0 => y * 2
       _ => -1
    }
    

    How compiler would know whether _ => -1 belongs to the first case scenario or represents the next case?

    Moreover, how compiler would know that the => sign doesn't represent a literal function but the actual code for the current case?

    Compiler would certainly need a kind of code like this allowing cases isolation: (using curly braces, or anything else)

    x match {
        {y if y > 0 => y * 2}
        {_ => -1}  // confusing with literal function notation
    }
    

    And surely, solution (provided currently by scala) using case keyword is a lot more readable and understandable than putting some way of separation like curly braces in my example.

提交回复
热议问题