Functional Purity

Purity means that functions have no side effects. The output of a function is predictably the same as long as the input is the same. A pure function isn’t affected by and doesn’t affect anything outside; it also doesn’t mutate any value.

There are two benefits of function purity. First, it’s easier to understand and prove the correctness of a pure function. Second, pure functions promote referential transparency. Pure functions can be easily rearranged and reordered for execution on multiple threads, making it easier to program concurrency on multicore processors.

Scala does not enforce purity, though it makes it easy to detect where mutable variables are used—simply search for vars. It is good Scala practice to use immutability ...

Get Functional Programming: A PragPub Anthology 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.