Scala coding styles and conventions?

后端 未结 7 822
野的像风
野的像风 2020-12-30 04:10

I think Scala goes too far from simplicity, like its syntax. For example Martin Odersky wrote the method in his book :

def calculate(s: String): Int =
  if (         


        
7条回答
  •  执笔经年
    2020-12-30 04:39

    Here is a link to the Scala Style Guide.


    The Curly Braces section says:

    Curly-Braces:

    Curly-braces should be omitted in cases where the control structure represents a pure- functional operation and all branches of the control structure (relevant to if/else) are single-line expressions. Remember the following guidelines:

    • if - Omit braces if you have an else clause. Otherwise, surround the contents with curly braces even if the contents are only a single line.

    • while - Never omit braces (while cannot be used in a pure-functional manner).

    • for - Omit braces if you have a yield clause. Otherwise, surround the contents with curly-braces, even if the contents are only a single line.

    • case - Omit braces if the case expression ts on a single line. Otherwise, use curly braces for clarity (even though they are not required by the parser).

      val news = if (foo)
        goodNews()
      else
        badNews()
      
      if (foo) {
        println("foo was true")
      }
      
      news match {
        case "good" => println("Good news!")
        case "bad" => println("Bad news!")
      }
      

    I wish people followed this style guide :(


    Please note that I don't agree with "Omit braces if if has an else clause" part. I'd much prefer to see the code like this:

    def calculate(s: String): Int = {
      if (cache.contains(s)) {
        cache(s)
      } else {
        val acc = new ChecksumAccumulator
        for (c <- s) {
          acc.add(c.toByte)
        }
        val cs = acc.checksum()
        cache += (s -> cs)
        cs
      }
    }
    

提交回复
热议问题