20.1. Create Methods with No Side Effects (Pure Functions)


In keeping with the best practices of Functional Programming (FP), you want to write “pure functions.”


In general, when writing a function (or method), your goal should be to write it as a pure function. This raises the question, “What is a pure function?” Before we tackle that question we need to look at another term, referential transparency, because it’s part of the description of a pure function.

Referential transparency

If you like algebra, you’ll like referential transparency. An expression is referentially transparent (RT) if it can be replaced by its resulting value without changing the behavior of the program. This must be true regardless of where the expression is used in the program.

For instance, assume that x and y are immutable variables within some scope of an application, and within that scope they’re used to form this expression:

x + y

You can assign this expression to a third variable, like this:

val z = x + y

Now, throughout the given scope of your program, anywhere the expression x + y is used, it can be replaced by z without affecting the result of the program.

Note that although I stated that x and y are immutable variables, they can also be the result of RT functions. For instance, "hello".length + "world".length will always be 10. This result could be assigned to z, and then z could be used everywhere instead of this expression.

Although this is a simple example, this is referential transparency ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.