Reassignable variable in purely functional code

I came across this classes in functional programming in scala 4 edition and book say that if Keyed is purely functional then MemoKeyed is purely functional. Does it mean we can sometimes have variable and assign value and still have purely functional code?

class Keyed {
    def computeKey: Int = ... // this will take some time

class MemoKeyed extends Keyed {
    private var keyCache: Option[Int] = None
    override def computeKey: Int = {
    if (!keyCache.isDefined) keyCache = Some(super.computeKey)

Well, this mostly depends on what is your definition of “purely functional code”.
In this case, the authors are using the concept of referential transparency as such a definition.

referential transparency is a simple concept it justs says that if you have x = y then you can replace all occurrences of x with y (and vice versa) without affecting the behaviour of the program.

So in this case, if Keyed.computeKey is “pure” (given the above definition) then MemoKeyed.computeKey is also “pure” for the perspective of the caller.

1 Like