September 2018
Intermediate to advanced
398 pages
9h 43m
English
In the following code, the pureSquare function is pure:
def pureSquare(x: Int): Int = x * xval pureExpr = pureSquare(4) + pureSquare(3)// pureExpr: Int = 25val pureExpr2 = 16 + 9// pureExpr2: Int = 25
The functions called pureSquare(4) and pureSquare(3) are referentially transparent—when we replace them with the return value of the function, the program's behavior does not change.
On the other hand, the following function is impure:
var globalState = 1def impure(x: Int): Int = { globalState = globalState + x globalState}val impureExpr = impure(3)// impureExpr: Int = 4val impureExpr2 = 4
We cannot replace the call to impure(3) with its return value because the return value changes depending on the context. In fact, ...
Read now
Unlock full access