Home > Articles > Programming

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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 = {
  ...
}
  • + Share This
  • 🔖 Save To Your Account