Mahsa
Mahsa

Reputation: 1550

How to reassign value to def in scala

I am writing a parser in which I have the following function:

    def lastop:(Either[RDD[(Int,Array[Float])], Float], Either[RDD[(Int,Array[Float])], Float]) => RDD[(Int,Array[Float])] = add

In which "add" is a function to perform addition. Then I want to use it in my program like the following line:

 terms.foreach(t =>
    t match { case nums ~ op => lastop = op; stack = reduce(stack ++ nums, op)}

I am getting the following error:

[error] /home/mahsa/calculator/temp/ScalaParser.scala:183: reassignment to val
[error]         t match { case nums ~ op => lastop = op; stack = reduce(stack ++ nums, op)}
[error]                                            ^

Can't figure how to solve this error!

Upvotes: 0

Views: 310

Answers (1)

Karl
Karl

Reputation: 1230

You want to store a changing reference to the function you want to invoke. If you are storing and reassigning something, that implies you need a var, not a val or a def. Try declaring lastop like:

var lastop:(Either[RDD[(Int,Array[Float])], Float], Either[RDD[(Int,Array[Float])], Float]) => RDD[(Int,Array[Float])] = add

Note that you will still need to invoke lastop like a function, since retrieving the var's value will return a function. It's a subtle but significant difference.

Upvotes: 2

Related Questions