Methods and Side Effects [Edit]
- One-line methods: simple expressions
- Side-effecting methods
- Return types
One-line methods: simple expressions
One-line methods with simple expressions do not require braces:
// preferred
def hasNext: Boolean = (i < end)
// hmmm-kay
def hasNext: Boolean = {
i < end
}
Side-effecting methods
One-line methods with side-effects should use braces (instead of using equal),
// preferred
def next() {
i += 1
}
// hmmm-kay
def next() { i += 1 }
// wrong: no parenthesis indicating effect
def next { i += 1 }
// wrong: equal sign shouldn't be used for Unit-returning methods
def next() = { i += 1 }
// wrong: equal sign shouldn't be used for Unit-returning methods
def next() = {
i += 1
}
Return types
Public and protected methods should explicitly declare their return type:
// good
def compute: Result = {
...
}
// wrong: no explicit result type
def compute = {
...
}
This practice avoids 1) having class users and inheritors having to guess the actual return type and 2) having the return type inadvertently change and thefore avoid unexpected incompatible class changes.
The rule also applies to methods returning Unit.
// hmmmm, questionable
def doSomething {
...
}
// preferred
def doSomething: Unit = {
}
And applies to abstract methods, e.g., in traits or abstract classes,
// good
trait Foo {
def compute: Result
def doSomething: Unit
}
// wrong
trait Foo {
def compute: Result
def doSomething() // missing "Unit"
}