
上QQ阅读APP看书,第一时间看更新
Referential transparency
In Scala, referential transparency (RT) means that an expression or a function call may be replaced by its value, without changing the behavior of the application.
A value may be replaced by an expression or a function call without changing the behavior of the application.
We will explore these two points with some simple examples now.
Let's assume that we are using the y = x + 1 expression in our application:
scala> val x = 10 x: Int = 10 scala> val y = x + 1 y: Int = 11 scala> val y = 11 y: Int = 11
Here, when we replace an expression x+1 with its value 11, it does not change any behavior of the y in our application:
scala> val y = 11 y: Int = 11 scala> def addOne(a: Int) = a + 1 addOne: (a: Int)Int scala> val y = addOne(x) y: Int = 11
Here, the value of y is replaced by a function called addOne(). In this case too, there is no change in the behavior of our application.
RT means an expression can be replaced with its value without changing its behavior.