Scala part 4: Don’t miss these rules

Hi everyone,

Today, I write the last part of Scala seriese. It includes somethings basic about Scala coding rules from this site http://docs.scala-lang.org/style

Indentation

Indentation should follow the “2-space convention”. Thus, instead of indenting like this:

    // right!
    class Foo {
      def bar = ..
    }

Line Wrapping

80 characters max per line

    val result = 1 + 2 + 3 + 4 + 5 + 6 +
      7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 +
      15 + 16 + 17 + 18 + 19 + 20

Method

    // right!
    val myOnerousAndLongFieldNameWithNoRealPoint =
      foo(
        someVeryLongFieldName,
        andAnotherVeryLongFieldName,
        "this is a string",
        3.1415)

    // wrong!
    val myOnerousAndLongFieldNameWithNoRealPoint = foo(someVeryLongFieldName,
    andAnotherVeryLongFieldName,
    "this is a string",
    3.1415)

Classes/Traits

    class MyFairLady

Objects

    object ast {
       sealed trait Expr
      case class Plus(e1: Expr, e2: Expr) extends Expr
      ...
    }

    object inc {
      def apply(x: Int): Int = x + 1
    }

Packages

    // wrong!
    package coolness
    // right!
    package com.novell.coolness
    // right, for package object com.novell.coolness
    package com.novell
    /**
    * Provides classes related to coolness
    */
    package object coolness {
    }

Methods

    def myFairMethod = ...

Constants, Values, Variable and Methods

    object Container {
      val MyConstant = ...
    }

    val myValue = ...
    def myMethod = ...
    var myVariable

Special Note on Brevity

    def add(a: Int, b: Int) = a + b

Declarations

    class Person(name: String, age: Int) {
    }

    class Person(
        name: String,
        age: Int,
        birthdate: Date,
        astrologicalSign: String,
        shoeSize: Int,
        favoriteColor: java.awt.Color) {      
      def firstMethod: Foo = ...
    }

Add a Comment

Scroll Up