- 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.10 Procedures
Scala has a special notation for a function that returns no value. If the function body is enclosed in braces without a preceding = symbol, then the return type is Unit. Such a function is called a procedure. A procedure returns no value, and you only call it for its side effect. For example, the following procedure prints a string inside a box, like
------- |Hello| -------
Because the procedure doesn’t return any value, we omit the = symbol.
def box(s : String) { // Look carefully: no = val border = "-" * s.length + "--\n" println(border + "|" + s + "|\n" + border) }
Some people (not me) dislike this concise syntax for procedures and suggest that you always use an explicit return type of Unit:
def box(s : String): Unit = { ... }