sarthak sarthak - 1 year ago 90
Scala Question

Passing function arguments by Name Scala

I have the following scala code. In this code, I am passing a (global) string name to a function and want to change the string depending on the first argument as shown below:

def retVal(x: (String,String), y: => String) = {if (x._1 != "") {y = x._1;x} else (y,x._2)}

But when I run this code, I get the following error:

y = x._1
reassignment to a val

How can I modify the code, so that I get the global string variable get updated when I call this function?

Answer Source

Function arguments are by default immutable in Scala. You cannot assign the a value to the function parameter.

In your case you are trying to assign to a call by name param which is not at all possible.

Also mutating is bad instead return the value and assign it to a new variable.

But still if you want to mutate do something like this

object MutationBox {
 var globalString = ""

 def retVal(x: (String,String)) = {
  if (x._1.nonEmpty) {
    globalString = x._1
   } else (globalString, x._2)


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download