Line Wrapping [Edit]
- Line Length and Indentation
- Wrapping expression in parenthesis
- Single expression
- Class definition
- Single expression method body
Line Length and Indentation
The recommended maximum line length is 120 characters.
Indentation for wrapped lines is 4 spaces.
Wrapping expression in parenthesis
There are two ways to wrap lines safely in Scala. It’s possible to leave a trailing operator,
// wrong
val result = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20 + 21 + 22 + 23 +
24 + 25 + 26 + 27 + 28 + 29 + 30 + 31 + 32 + 33
or it’s possible to wrap everything in a set of parenthesis without need for trailing operators:
// right
val result = (
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20 + 21 + 22 + 23 + 24 + 25
+ 26 + 27 + 28 + 29 + 30 + 31 + 32 + 33
)
We prefer wrapping in a set of parenthesis and starting new lines with operators because it’s easier to mentally connect operations and arguments (see below).
Single expression
// wrong
private val socketTimeout = (Option(config.getProperty("socketTimeout")) map (_.toInt)
getOrElse defaultSocketTimeout)
// right
private val socketTimeout = (
Option(config.getProperty("socketTimeout"))
map (_.toInt)
getOrElse defaultSocketTimeout
)
As you can see above, it’s a good idea to wrap for each operator-and-arguments pair.
Here are more examples,
// passable
def foo: List[Int] = (1 to 100).view.map { _ + 3 }.filter { _ > 10 }.flatMap { table.get }.take(3).toList
// good
def foo: List[Int] = (
(1 to 100).view
map { _ + 3 }
filter { _ > 10 }
flatMap { table.get }
take (3)
toList
)
// wrong
def bar = Console.println(io.Source.fromFile("names.txt").getLines.mkString.split(",").map{x:String => x.slice(1, x.length -1)}.sortBy { x => x}.zipWithIndex.map{t =>{ (t._2 +1)*(t._1.map{_.toChar - "A"(0).toChar + 1}.sum)}}.sum);
// better
def bar = Console.println(
io.Source.fromFile("names.txt").getLines.mkString.split(",")
map { x:String => x.slice(1, x.length - 1) }
sortBy { x => x}
zipWithIndex
map { t => { (t._2 +1) * (t._1 map { _.toChar - "A"(0).toChar + 1}.sum) } }
sum
)
Class definition
// wrong
class SugarcubeServer(val catalog: Catalog, val databases: Seq[String],
val config: Properties = new Properties()) extends ThriftServer with JettyServer {
...
}
// right
class SugarcubeServer(
val catalog: Catalog,
val databases: Seq[String],
val config: Properties = new Properties()
) extends ThriftServer with JettyServer {
...
}
Single expression method body
// preferred
def fib(n: Int, b: Int, a: Int): Int = n match {
case 0 => a
case _ => fib(n - 1, a + b, b)
}
// hmmm-kay
def fib(n: Int, b: Int, a: Int): Int = {
n match {
case 0 => a
case _ => fibonacci(n - 1, a + b, b)
}
}