- 2.1 Conditional Expressions
- 2.2 Statement Termination
- 2.3 Block Expressions and Assignments
- 2.4 Input and Output
- 2.5 Loops
- 2.6 Advanced for Loops and for Comprehensions
- 2.7 Functions
- 2.8 Default and Named Arguments L1
- 2.9 Variable Arguments L1
- 2.10 Procedures
- 2.11 Lazy Values L1
- 2.12 Exceptions
- Exercises
2.2 Statement Termination
In Java and C++, every statement ends with a semicolon. In Scala—like in JavaScript and other scripting languages—a semicolon is never required if it falls just before the end of the line. A semicolon is also optional before an }, an else, and similar locations where it is clear from context that the end of a statement has been reached.
However, if you want to have more than one statement on a single line, you need to separate them with semicolons. For example,
if (n > 0) { r = r * n; n -= 1 }
A semicolon is needed to separate r = r * x and n -= 1. Because of the }, no semicolon is needed after the second statement.
If you want to continue a long statement over two lines, you need to make sure that the first line ends in a symbol that cannot be the end of a statement. An operator is often a good choice:
s = s0 + (v - v0) * t + // The + tells the parser that this is not the end 0.5 * (a - a0) * t * t
In practice, long expressions usually involve function or method calls, and then you don’t need to worry much—after an opening (, the compiler won’t infer the end of a statement until it has seen the matching ).
In the same spirit, Scala programmers favor the Kernighan & Ritchie brace style:
if (n > 0) { r = r * n n -= 1 }
The line ending with a { sends a clear signal that there is more to come.
Many programmers coming from Java or C++ are initially uncomfortable about omitting semicolons. If you prefer to have them, just put them in—they do no harm.